Compare commits

..
Author SHA1 Message Date
FredApps 9224484b61 fix(cli): collapse the sandbox-check usage if for clippy 2026-12-02 21:09:28 +01:00
FredApps 80ebfe9566 fix(cli): address RFC-0018 CodeRabbit findings on the clap rewrite
Refuse convert and run --out when they would replace the input, unless
--overwrite is passed, and check that before a run script starts. Accept
eval -- --1 as a formula, allow negative JSON on send, reject
sandbox-check -- with no program, convert check paths with unicode(),
drop the numeric --sheet selector after activation, write MCP replies to
the run() writer, and report help/version write failures other than a
closed pipe. The no-program sandbox self-test only runs through the
CLI binary. The FreeBSD packager builds the docs generator for the host,
and the Linux nightly rename touches only the asset basename.
2026-12-02 21:06:41 +01:00
FredApps 3c43bce2b1 Merge main into rfc-0018-gridcraft-cli
Keep the clap rewrite of gridcraft-cli. Port main's save/open warning
coverage (file.save, file.saveAs, file.saveBytes, and convert save_losses)
onto the new command path.
2026-12-02 20:55:28 +01:00
FredApps 494f8e06cd packaging tests: stub the man-and-completions example the Linux package script now runs 2026-11-27 00:56:05 +01:00
FredApps ee56426417 gridcraft-cli: follow RFC-0018 (clap, thiserror, run(args, out, err), packaged completions and man pages) 2026-11-27 00:44:42 +01:00
157 changed files with 2524 additions and 10053 deletions
Generated
+143 -1
View File
@@ -199,12 +199,56 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]]
name = "anyhow"
version = "1.0.104"
@@ -796,6 +840,65 @@ dependencies = [
"libloading",
]
[[package]]
name = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_complete"
version = "4.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "clap_mangen"
version = "0.2.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78"
dependencies = [
"clap",
"roff",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -873,6 +976,12 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "colored"
version = "2.2.0"
@@ -2904,12 +3013,16 @@ dependencies = [
name = "gridcraft-cli"
version = "0.20.0"
dependencies = [
"clap",
"clap_complete",
"clap_mangen",
"gridcraft-engine",
"gridcraft-mcp",
"gridcraft-sandbox",
"log",
"quick-xml 0.42.0",
"serde_json",
"thiserror 2.0.21",
"zip",
]
@@ -3050,7 +3163,6 @@ dependencies = [
"craft-host",
"craft-keymap",
"craft-print",
"craft-quit",
"craft-theme",
"craft-ui",
"craft-update",
@@ -3737,6 +3849,12 @@ dependencies = [
"once_cell",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.13.0"
@@ -4798,6 +4916,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "open"
version = "5.4.4"
@@ -5733,6 +5857,12 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "roff"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
[[package]]
name = "roxmltree"
version = "0.21.2"
@@ -6503,6 +6633,12 @@ dependencies = [
"float-cmp",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.28.0"
@@ -7209,6 +7345,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.27.0"
+4 -1
View File
@@ -58,6 +58,10 @@ craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a
# foundation
thiserror = "2"
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
clap = { version = "4", features = ["derive"] }
clap_complete = "4"
clap_mangen = "0.2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
log = "0.4"
@@ -105,7 +109,6 @@ craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
[workspace.lints.rust]
unsafe_code = "forbid"
-29
View File
@@ -275,37 +275,8 @@ handling again for troubleshooting.
| Fedora/RHEL/openSUSE | `gridcraft-<ver>-linux-x86_64.rpm` | `gridcraft-<ver>-linux-aarch64.rpm` | |
| Tarball | `gridcraft-<ver>-linux-x86_64.tar.gz` | `gridcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
#### Community packages
These packages are maintained by community members, not by the GridCraft team, and the project
does not review them. An overlay's ebuilds run as root when you install a package, so read the
ebuild before you emerge it.
On Gentoo, the [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages the
Linux release as `app-office/gridcraft-bin` (prebuilt) and `app-office/gridcraft` (built from source).
`gridcraft-bin` downloads `gridcraft-<ver>-linux-x86_64.tar.gz` from this repository's releases, and
Portage refuses the file unless it matches the overlay's `Manifest`. To check that it is the
release's own file before installing it, fetch it first with `emerge --fetchonly`, run `sha256sum`
on it in your `DISTDIR` and compare with the release's `SHA256SUMS.txt`.
```sh
emerge --ask --noreplace app-eselect/eselect-repository
eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git
emaint sync -r snakebyte
# package.accept_keywords can be a directory or a single file
if [ -d /etc/portage/package.accept_keywords ]; then
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/gridcraft
else
echo 'app-office/gridcraft-bin ~amd64' >> /etc/portage/package.accept_keywords
fi
emerge --fetchonly app-office/gridcraft-bin # then check the file in DISTDIR as above
emerge --ask app-office/gridcraft-bin
```
### FreeBSD
Current prebuilt FreeBSD downloads require FreeBSD 15.1 or later; they are not compatible with FreeBSD 14.x.
| Build | File |
|---|---|
| x86_64 | `gridcraft-<ver>-freebsd-x86_64.tar.gz` |
+11
View File
@@ -9,6 +9,10 @@ publish = false
[lints]
workspace = true
[lib]
name = "gridcraft_cli"
path = "src/lib.rs"
[[bin]]
name = "gridcraft-cli"
path = "src/main.rs"
@@ -22,3 +26,10 @@ log = { workspace = true }
# `check`: validating the packages GridCraft writes (content types, relationships).
zip = { workspace = true }
quick-xml = { workspace = true }
thiserror = { workspace = true }
clap = { workspace = true }
[dev-dependencies]
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
clap_complete = { workspace = true }
clap_mangen = { workspace = true }
@@ -0,0 +1,42 @@
//! Writes gridcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
//! PowerShell) and man pages ([`clap_mangen`]: `gridcraft-cli.1` and one per subcommand, such as
//! `gridcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
//! (see `packaging/`):
//!
//! ```sh
//! cargo run -p gridcraft-cli --example man-and-completions -- <out-dir>
//! ```
use std::path::Path;
use std::process::ExitCode;
use clap::ValueEnum;
use clap_complete::Shell;
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let (Some(dir), None) = (args.next(), args.next()) else {
eprintln!("usage: man-and-completions <out-dir>");
return ExitCode::from(2);
};
let dir = Path::new(&dir);
match generate(dir) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {}: {e}", dir.display());
ExitCode::FAILURE
}
}
}
/// Also run by the tests.
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let mut cmd = gridcraft_cli::command();
for &shell in Shell::value_variants() {
clap_complete::generate_to(shell, &mut cmd, "gridcraft-cli", dir)?;
}
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
// which `clap_mangen` would otherwise give pages of its own (`gridcraft-cli-help-convert.1`).
clap_mangen::generate_to(gridcraft_cli::command(), dir)
}
+321
View File
@@ -0,0 +1,321 @@
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string;
//! what clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
//!
//! `run` is ordered: its `--cmd` and `--script` steps run in the order they were given, so the repeatable options are
//! kept with their positions and read back in order ([`RunArgs::steps`]).
use std::ffi::OsString;
use std::path::PathBuf;
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use serde_json::Value;
use crate::script::{ScriptError, Step, parse_command};
/// The end of every subcommand's `--help`.
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// The top-level `--help` ends with the environment and the exit status.
const TOP_NOTES: &str = "Environment:\n none: the CLI reads no environment variables of its own\n\nExit status:\n 0 success\n 1 the command failed (for `check`, a difference was found)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// What a script line looks like (the `run` help ends with it).
const SCRIPT_LINES: &str = "A script line is `id={json}`, `id {json}`, `id`, or {\"command\": \"id\", \"params\": {…}}; blank lines and lines starting with # or // are skipped.";
/// Headless GridCraft: inspect, convert, evaluate, script and serve MCP without a window
#[derive(Parser, Debug)]
#[command(name = "gridcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
}
#[derive(Subcommand, Debug)]
pub(crate) enum Command {
/// Sheets, used ranges, tables, charts and names of a workbook
#[command(after_help = EXIT_STATUS)]
Info(InfoArgs),
/// Convert a workbook: xlsx, csv, tsv, json, html or pdf, by the extension of OUT
#[command(after_help = EXIT_STATUS)]
Convert(ConvertArgs),
/// Evaluate one formula, optionally against a workbook
#[command(after_help = EXIT_STATUS)]
Eval(EvalArgs),
/// Print a range as an aligned table or CSV
#[command(after_help = EXIT_STATUS)]
Cat(CatArgs),
/// Cached-value calc oracle and XLSX round-trip fidelity of files or folders (exit 1 on any difference)
#[command(after_help = EXIT_STATUS)]
Check(CheckArgs),
/// Run commands and scripts on a workbook, then save or print it
#[command(after_help = format!("{SCRIPT_LINES}\n\n{EXIT_STATUS}"))]
Run(RunArgs),
/// List the commands
#[command(after_help = EXIT_STATUS)]
Commands(ListArgs),
/// List the formula functions
#[command(after_help = EXIT_STATUS)]
Functions(FunctionsArgs),
/// Serve MCP on stdio, headless or driving the running app
#[command(after_help = EXIT_STATUS)]
Mcp(McpArgs),
/// Send one control-channel request to the running app
#[command(after_help = EXIT_STATUS)]
Send(SendArgs),
/// Whether this system confines programs (no program: a confined self-test)
///
/// With a program it runs that program confined, with the given read and executable paths and the system's shared
/// libraries, passing its output and exit status through; its own lines then go to standard error. Every path is
/// absolute. Exit status: 0 when every attempt is as required (or the program succeeded), 1 otherwise (a refused
/// launch included), 2 when GridCraft has no sandbox for this kind of system.
#[command(name = "sandbox-check", after_help = EXIT_STATUS)]
SandboxCheck(SandboxCheckArgs),
}
#[derive(Args, Debug)]
pub(crate) struct InfoArgs {
/// The workbook
pub(crate) file: PathBuf,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct ConvertArgs {
/// The workbook to read
pub(crate) input: PathBuf,
/// The file to write (.xlsx, .csv, .tsv, .json, .html or .pdf)
pub(crate) output: PathBuf,
/// The sheet to write, by name or index
#[arg(long, value_name = "NAME")]
pub(crate) sheet: Option<String>,
/// Allow OUTPUT to replace the input workbook
#[arg(long)]
pub(crate) overwrite: bool,
}
#[derive(Args, Debug)]
pub(crate) struct EvalArgs {
/// The formula; a leading `=` is optional
#[arg(allow_hyphen_values = true)]
pub(crate) formula: String,
/// Evaluate against this workbook
#[arg(long = "in", value_name = "FILE")]
pub(crate) input: Option<PathBuf>,
/// The sheet to evaluate on, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// The cell the formula sits in
#[arg(long, value_name = "A1")]
pub(crate) cell: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CatArgs {
/// The workbook
pub(crate) file: PathBuf,
/// The range to print (default: the used range)
#[arg(long, value_name = "A1:D20")]
pub(crate) range: Option<String>,
/// The sheet to print, by name or index
#[arg(long, value_name = "S")]
pub(crate) sheet: Option<String>,
/// Show formulas instead of values
#[arg(long)]
pub(crate) formulas: bool,
/// Print CSV instead of an aligned table
#[arg(long)]
pub(crate) csv: bool,
}
#[derive(Args, Debug)]
pub(crate) struct CheckArgs {
/// Files to check, or folders to scan for .xlsx and .xlsm files
#[arg(required = true, value_name = "FILE_OR_DIR")]
pub(crate) inputs: Vec<PathBuf>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
/// How far a cached number may differ from the recalculated one
#[arg(long, value_name = "T", allow_negative_numbers = true, value_parser = tolerance)]
pub(crate) tolerance: Option<f64>,
/// How many mismatches to list per file
#[arg(long = "max-report", value_name = "N")]
pub(crate) max_report: Option<usize>,
}
fn tolerance(text: &str) -> Result<f64, UsageError> {
text.parse().ok().filter(|t: &f64| t.is_finite() && *t >= 0.0).ok_or_else(|| UsageError::Tolerance(text.to_owned()))
}
/// The command or the script file of a `run` step.
#[derive(Clone, Debug)]
pub(crate) enum RunStep {
/// `--cmd`; a blank or comment line is `None`.
Cmd(Option<Step>),
/// `--script`
Script(PathBuf),
}
#[derive(Args, Debug)]
pub(crate) struct RunArgs {
/// Start from this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Start from a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
/// Run one command, `ID={json}`; repeatable, in order with `--script`
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = command_step)]
cmds: Vec<Option<Step>>,
/// Run a script file of command lines (.jsonl); repeatable, in order with `--cmd`
#[arg(long = "script", value_name = "FILE")]
scripts: Vec<PathBuf>,
/// Save the workbook here when the steps are done (by extension)
#[arg(long, value_name = "FILE")]
pub(crate) out: Option<PathBuf>,
/// Allow `--out` to replace `--in`
#[arg(long, requires = "out")]
pub(crate) overwrite: bool,
/// Print a range when the steps are done (`used` or empty: the used range); repeatable
#[arg(long, value_name = "RANGE")]
pub(crate) print: Vec<String>,
/// The sheet `--print` shows, by name or index
#[arg(long, value_name = "S", requires = "print")]
pub(crate) sheet: Option<String>,
/// `--print` shows formulas instead of values
#[arg(long, requires = "print")]
pub(crate) formulas: bool,
/// `--print` writes CSV instead of an aligned table
#[arg(long, requires = "print")]
pub(crate) csv: bool,
/// Don't print each command's result
#[arg(long)]
pub(crate) quiet: bool,
/// The steps in the order they were given.
#[arg(skip)]
pub(crate) steps: Vec<RunStep>,
}
/// The values of a repeatable option with the position each was given at.
fn at<T: Clone>(sub: &ArgMatches, id: &str, values: &[T]) -> Vec<(usize, T)> {
sub.indices_of(id).into_iter().flatten().zip(values.iter().cloned()).collect()
}
impl RunArgs {
fn check(&mut self, sub: &ArgMatches) {
let mut steps: Vec<(usize, RunStep)> = at(sub, "cmds", &self.cmds).into_iter().map(|(i, c)| (i, RunStep::Cmd(c))).collect();
steps.extend(at(sub, "scripts", &self.scripts).into_iter().map(|(i, p)| (i, RunStep::Script(p))));
steps.sort_by_key(|(i, _)| *i);
self.steps = steps.into_iter().map(|(_, s)| s).collect();
}
}
fn command_step(text: &str) -> Result<Option<Step>, UsageError> {
parse_command(text).map_err(UsageError::Cmd)
}
#[derive(Args, Debug)]
pub(crate) struct ListArgs {
/// Only those whose id, label or menu contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct FunctionsArgs {
/// Only those whose name or description contains this
#[arg(value_name = "SEARCH", conflicts_with = "search")]
pub(crate) word: Option<String>,
/// The same, as an option
#[arg(long, value_name = "X")]
pub(crate) search: Option<String>,
/// Only this category
#[arg(long, value_name = "C")]
pub(crate) category: Option<String>,
/// JSON alone on stdout
#[arg(long)]
pub(crate) json: bool,
}
#[derive(Args, Debug)]
pub(crate) struct McpArgs {
/// Drive the running app (started with `gridcraft --control PORT`) instead of a headless workbook
#[arg(long, value_name = "PORT", conflicts_with_all = ["input", "sample"])]
pub(crate) connect: Option<String>,
/// Serve this workbook
#[arg(long = "in", value_name = "FILE", conflicts_with = "sample")]
pub(crate) input: Option<PathBuf>,
/// Serve a sample workbook
#[arg(long, value_name = "NAME")]
pub(crate) sample: Option<String>,
}
#[derive(Args, Debug)]
pub(crate) struct SendArgs {
/// The control port of the running app
pub(crate) port: String,
/// The control-channel method
pub(crate) method: String,
/// Its parameters, as JSON
#[arg(value_name = "JSON", allow_negative_numbers = true, value_parser = json_value)]
pub(crate) params: Option<Value>,
}
fn json_value(text: &str) -> Result<Value, UsageError> {
serde_json::from_str(text).map_err(|e| UsageError::Json(e.to_string()))
}
#[derive(Args, Debug)]
pub(crate) struct SandboxCheckArgs {
/// Let the program read this path; repeatable
#[arg(long, value_name = "PATH")]
pub(crate) read: Vec<PathBuf>,
/// Let the program execute this path; repeatable
#[arg(long = "exec", value_name = "PATH")]
pub(crate) exec: Vec<PathBuf>,
/// After `--`: the program to run confined, and its arguments
#[arg(last = true, value_name = "PROGRAM")]
pub(crate) program: Vec<OsString>,
}
/// A mistake in the command line that clap can't see by itself.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum UsageError {
#[error("--tolerance: expected a number ≥ 0, not `{0}`")]
Tolerance(String),
#[error("--cmd: {0}")]
Cmd(ScriptError),
#[error("bad JSON params: {0}")]
Json(String),
}
/// The clap definition of the whole command line (completions and man pages are generated from it).
pub fn command() -> clap::Command {
Cli::command()
}
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("gridcraft-cli")).chain(args.iter().cloned()))?;
let mut cli = Cli::from_arg_matches(&matches)?;
if let (Command::Run(run), Some(("run", sub))) = (&mut cli.command, matches.subcommand()) {
run.check(sub);
}
if let Command::SandboxCheck(check) = &cli.command
&& check.program.is_empty()
&& args.iter().any(|arg| arg == "--")
{
return Err(Cli::command().error(clap::error::ErrorKind::InvalidValue, "sandbox-check: a program is required after `--`"));
}
Ok(cli)
}
+15 -29
View File
@@ -15,7 +15,6 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::{Cursor, Read as _};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use gridcraft_engine::calc::{Calc, Key};
use gridcraft_engine::cmd::inspect::value_json;
@@ -24,7 +23,10 @@ use gridcraft_engine::formula::{Expr, quote_sheet};
use gridcraft_engine::model::{Cell, Sheet, Workbook};
use serde_json::{Value as Json, json};
use super::{Args, USAGE, number_text, pretty};
use crate::args::CheckArgs;
use crate::commands::{number_text, pretty};
use crate::error::{CliError, unicode};
use crate::{Io, outln};
mod calc;
mod fidelity;
@@ -189,32 +191,16 @@ impl Diffs {
/// `check <file-or-dir>... [--json] [--tolerance X] [--max-report N]`. Exit 0 when every file opens,
/// every checked formula matches and every round trip is clean; 1 otherwise; 2 on a usage error.
pub fn main(args: &[String]) -> ExitCode {
let usage = |e: String| {
eprintln!("gridcraft-cli: {e}\n{USAGE}");
ExitCode::from(2)
};
let a = match Args::parse(args, &["tolerance", "max-report"], &["json"]) {
Ok(a) => a,
Err(e) => return usage(e),
};
if a.positional.is_empty() {
return usage("missing <file-or-dir>".into());
}
pub(crate) fn run(a: &CheckArgs, io: &mut Io) -> Result<i32, CliError> {
let mut opts = Options::default();
if let Some(t) = a.opt("tolerance") {
match t.parse::<f64>() {
Ok(t) if t.is_finite() && t >= 0.0 => opts.tolerance = t,
_ => return usage(format!("--tolerance needs a number ≥ 0, not `{t}`")),
}
if let Some(t) = a.tolerance {
opts.tolerance = t;
}
if let Some(n) = a.opt("max-report") {
match n.parse::<usize>() {
Ok(n) => opts.max_report = n,
Err(_) => return usage(format!("--max-report needs a whole number, not `{n}`")),
}
if let Some(n) = a.max_report {
opts.max_report = n;
}
let Discovery { files, failures: mut reports, .. } = collect_inputs(&a.positional);
let inputs: Vec<String> = a.inputs.iter().map(|p| unicode(p).map(str::to_owned)).collect::<Result<_, _>>()?;
let Discovery { files, failures: mut reports, .. } = collect_inputs(&inputs);
reports.extend(files.iter().map(|p| {
let path = p.to_string_lossy().into_owned();
match gridcraft_engine::io::read_file(&path) {
@@ -222,12 +208,12 @@ pub fn main(args: &[String]) -> ExitCode {
Err(e) => FileReport { path, error: Some(e.to_string()), ..Default::default() },
}
}));
if a.has("json") {
outln!("{}", pretty(&report_json(&reports, &opts)));
if a.json {
outln!(io, "{}", pretty(&report_json(&reports, &opts)));
} else {
print_human(&reports, &opts);
print_human(io, &reports, &opts)?;
}
if !files.is_empty() && reports.iter().all(FileReport::is_clean) { ExitCode::SUCCESS } else { ExitCode::FAILURE }
Ok(if !files.is_empty() && reports.iter().all(FileReport::is_clean) { 0 } else { 1 })
}
#[derive(Default)]
+41 -31
View File
@@ -131,15 +131,16 @@ fn fit(s: &str, w: usize) -> String {
if n <= w { s.to_string() } else { format!("…{}", s.chars().skip(n + 1 - w).collect::<String>()) }
}
fn print_file_reports(reports: &[FileReport]) {
fn print_file_reports(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
for r in reports {
outln!("== {}", r.path);
outln!(io, "== {}", r.path);
if let Some(e) = &r.error {
outln!(" can't open: {e}");
outln!(io, " can't open: {e}");
continue;
}
let c = &r.calc;
outln!(
io,
" formulas {}: {} checked, {} matched, {} mismatched, {} no oracle, {} volatile",
c.formula_cells,
c.checked,
@@ -149,14 +150,15 @@ fn print_file_reports(reports: &[FileReport]) {
c.volatile
);
if c.stale_cache {
outln!(" (the producer asked for a full recalculation on load: its cached values aren't results)");
outln!(io, " (the producer asked for a full recalculation on load: its cached values aren't results)");
}
if c.bool_as_number > 0 {
outln!(" ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
outln!(io, " ({} matched TRUE/FALSE results were saved by the producer as 1/0, without t=\"b\")", c.bool_as_number);
}
for m in &c.mismatches {
let tag = if m.primary { "mismatch" } else { " (downstream)" };
outln!(
io,
" {tag} {} {} expected {} got {} [{}]",
m.cell,
one_line(&m.formula),
@@ -166,31 +168,33 @@ fn print_file_reports(reports: &[FileReport]) {
);
}
if c.mismatched > c.mismatches.len() {
outln!(" … {} more mismatches", c.mismatched - c.mismatches.len());
outln!(io, " … {} more mismatches", c.mismatched - c.mismatches.len());
}
let rt = &r.round_trip;
if let Some(e) = &rt.error {
outln!(" round trip: {e}");
outln!(io, " round trip: {e}");
}
let differing: Vec<&Category> = rt.categories.iter().filter(|c| c.diffs > 0).collect();
if differing.is_empty() && rt.error.is_none() {
outln!(" round trip: all equal");
outln!(io, " round trip: all equal");
}
for cat in differing {
outln!(" round trip {}: {} difference(s)", cat.name, cat.diffs);
outln!(io, " round trip {}: {} difference(s)", cat.name, cat.diffs);
for e in &cat.examples {
outln!(" {}", one_line(e));
outln!(io, " {}", one_line(e));
}
if cat.diffs > cat.examples.len() {
outln!(" … {} more", cat.diffs - cat.examples.len());
outln!(io, " … {} more", cat.diffs - cat.examples.len());
}
}
}
Ok(())
}
fn print_file_table(reports: &[FileReport]) {
fn print_file_table(io: &mut Io, reports: &[FileReport]) -> Result<(), CliError> {
let w = reports.iter().map(|r| r.path.chars().count()).max().unwrap_or(4).clamp(4, 50);
outln!(
io,
"{:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} round trip",
"file",
"formulas",
@@ -203,7 +207,7 @@ fn print_file_table(reports: &[FileReport]) {
for r in reports {
let label = fit(&r.path, w);
if let Some(e) = &r.error {
outln!("{label:<w$} can't open: {}", one_line(&fit(e, 100)));
outln!(io, "{label:<w$} can't open: {}", one_line(&fit(e, 100)));
continue;
}
let c = &r.calc;
@@ -213,6 +217,7 @@ fn print_file_table(reports: &[FileReport]) {
(None, d) => d.join(","),
};
outln!(
io,
"{label:<w$} {:>8} {:>8} {:>8} {:>8} {:>9} {:>8} {rt}",
c.formula_cells,
c.checked,
@@ -222,33 +227,36 @@ fn print_file_table(reports: &[FileReport]) {
c.volatile
);
}
Ok(())
}
fn print_rankings(t: &Totals, opts: &Options) {
fn print_rankings(io: &mut Io, t: &Totals, opts: &Options) -> Result<(), CliError> {
let top = ranked(&t.functions);
if !top.is_empty() {
outln!("");
outln!("top mismatching functions (primary = no mismatching precedent):");
outln!(" {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
outln!(io, "");
outln!(io, "top mismatching functions (primary = no mismatching precedent):");
outln!(io, " {:<20} {:>8} {:>10} {:>8}", "function", "primary", "mismatched", "checked");
for (n, s) in top.iter().take(opts.max_report.max(1)) {
outln!(" {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
outln!(io, " {:<20} {:>8} {:>10} {:>8}", n, s.primary, s.mismatched, s.checked);
}
}
let mut sigs: Vec<(&String, &usize)> = t.signatures.iter().collect();
sigs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
if !sigs.is_empty() {
outln!("");
outln!("mismatch signatures (expected → GridCraft):");
outln!(io, "");
outln!(io, "mismatch signatures (expected → GridCraft):");
for (sig, n) in sigs.iter().take(opts.max_report.max(1)) {
outln!(" {n:>8} {sig}");
outln!(io, " {n:>8} {sig}");
}
}
Ok(())
}
fn print_totals(t: &Totals) {
outln!("");
outln!("files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
fn print_totals(io: &mut Io, t: &Totals) -> Result<(), CliError> {
outln!(io, "");
outln!(io, "files: {} ({} opened, {} failed to open)", t.files, t.opened, t.failed);
outln!(
io,
"formula cells: {} ({} checked: {} matched, {} mismatched; {} no oracle; {} volatile)",
t.formula_cells,
t.checked,
@@ -258,23 +266,25 @@ fn print_totals(t: &Totals) {
t.volatile
);
if t.bool_as_number > 0 {
outln!("booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
outln!(io, "booleans saved as 1/0 by the producer: {} (counted as matched)", t.bool_as_number);
}
let cats: Vec<String> = t.categories.iter().map(|(c, n)| format!("{c} {n}")).collect();
outln!(
io,
"round trip: {} of {} files differ{}{}",
t.round_trip_differing,
t.opened,
if t.round_trip_failed > 0 { format!(" ({} failed)", t.round_trip_failed) } else { String::new() },
if cats.is_empty() { String::new() } else { format!("; categories (files): {}", cats.join(", ")) }
);
Ok(())
}
pub(super) fn print_human(reports: &[FileReport], opts: &Options) {
print_file_reports(reports);
outln!("");
print_file_table(reports);
pub(super) fn print_human(io: &mut Io, reports: &[FileReport], opts: &Options) -> Result<(), CliError> {
print_file_reports(io, reports)?;
outln!(io, "");
print_file_table(io, reports)?;
let t = totals(reports);
print_rankings(&t, opts);
print_totals(&t);
print_rankings(io, &t, opts)?;
print_totals(io, &t)
}
+468
View File
@@ -0,0 +1,468 @@
//! The subcommands: each takes its typed arguments and the streams, and returns what to exit with.
use std::path::Path;
use gridcraft_engine::Session;
use serde_json::{Value, json};
use crate::args::{CatArgs, Command, ConvertArgs, EvalArgs, FunctionsArgs, InfoArgs, ListArgs, McpArgs, RunArgs, RunStep, SendArgs};
use crate::error::{CliError, unicode};
use crate::script::parse_command;
use crate::{Io, check, errln, outln, sandbox_check};
/// Run a parsed command line; gives the exit code (0, or 1 when `check` found a difference and said so itself).
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<i32, CliError> {
match command {
Command::Info(a) => info(&a, io),
Command::Convert(a) => convert(&a, io),
Command::Eval(a) => eval(&a, io),
Command::Cat(a) => cat(&a, io),
Command::Run(a) => run(&a, io),
Command::Commands(a) => commands(&a, io),
Command::Functions(a) => functions(&a, io),
Command::Mcp(a) => mcp(&a, io),
Command::Send(a) => send(&a, io),
Command::Check(a) => return check::run(&a, io),
Command::SandboxCheck(a) => return sandbox_check::run(&a, io),
}
.map(|()| 0)
}
// ---------------------------------------------------------------- helpers
fn exec(io: &mut Io, s: &mut Session, id: &str, params: Value) -> Result<Value, CliError> {
let r = s.execute_headless(id, params).map_err(CliError::engine);
if matches!(id, "file.open" | "file.save" | "file.saveAs" | "file.saveBytes")
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
for warning in warnings.iter().filter_map(Value::as_str) {
errln!(io, "Warning: {warning}");
}
}
r
}
fn open(io: &mut Io, path: &std::path::Path) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.open", json!({"path": unicode(path)?}))?;
Ok(s)
}
fn sample(io: &mut Io, name: &str) -> Result<Session, CliError> {
let mut s = Session::new();
exec(io, &mut s, "file.new", json!({"sample": name}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(io: &mut Io, s: &mut Session, sheet: Option<&str>) -> Result<(), CliError> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(io, s, "sheet.activate", p)?;
}
Ok(())
}
pub(crate) fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
pub(crate) fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(a: &InfoArgs, io: &mut Io) -> Result<(), CliError> {
let path = unicode(&a.file)?;
let mut s = open(io, &a.file)?;
let v = exec(io, &mut s, "document.inspect", json!({}))?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
outln!(io, "{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
io,
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(
io,
" table {} {} ({})",
t["name"].as_str().unwrap_or("?"),
t["range"].as_str().unwrap_or("?"),
t["style"].as_str().unwrap_or("")
);
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(io, " chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(io, " filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!(io, "names:");
for n in names {
outln!(io, " {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
/// Whether `out` is the file `input` names: the same path, a symlink to it or, on Unix, a hard
/// link (the same device and inode). An `out` that doesn't exist yet can't be the input.
fn names_the_same_file(input: &Path, out: &Path) -> bool {
let (Ok(a), Ok(b)) = (std::fs::canonicalize(input), std::fs::canonicalize(out)) else { return false };
if a == b {
return true;
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let (Ok(a), Ok(b)) = (std::fs::metadata(&a), std::fs::metadata(&b)) {
return (a.dev(), a.ino()) == (b.dev(), b.ino());
}
}
false
}
fn refuse_replace(input: &Path, out: &Path, overwrite: bool) -> Result<(), CliError> {
if !overwrite && names_the_same_file(input, out) {
return Err(CliError::WouldReplace { out: out.to_owned(), input: input.to_owned() });
}
Ok(())
}
fn convert(a: &ConvertArgs, io: &mut Io) -> Result<(), CliError> {
refuse_replace(&a.input, &a.output, a.overwrite)?;
let out = unicode(&a.output)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(CliError::OutputFormat { out: out.to_owned() });
}
let mut s = open(io, &a.input)?;
activate_sheet(io, &mut s, a.sheet.as_deref())?;
if pdf {
let result = exec(io, &mut s, "file.exportPdf", json!({"path": out}))?;
errln!(io, "wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
return Ok(());
}
for warning in gridcraft_engine::cmd::file::save_losses(&s, "file.save", &json!({"path": out})).messages() {
errln!(io, "Warning: {warning}");
}
let d = s.doc().map_err(CliError::engine)?;
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(CliError::engine)?;
gridcraft_engine::io::write_file(out, &bytes).map_err(CliError::engine)?;
errln!(io, "wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(a: &EvalArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = match &a.input {
Some(p) => open(io, p)?,
None => blank(),
};
activate_sheet(io, &mut s, a.sheet.as_deref())?;
let formula = if a.formula.starts_with('=') { a.formula.clone() } else { format!("={}", a.formula) };
let mut p = json!({"formula": formula});
if let Some(c) = &a.cell {
p["cell"] = json!(c);
}
let v = exec(io, &mut s, "formulas.evaluate", p)?;
if a.json {
outln!(io, "{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!(io, "{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(io: &mut Io, s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), CliError> {
activate_sheet(io, s, sheet)?;
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
// Activation already selected a numeric `--sheet` index; `sheet.read` takes names only.
let raw = exec(io, s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(io, s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!(io, "{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!(io, "{}", line.trim_end());
}
Ok(())
}
fn cat(a: &CatArgs, io: &mut Io) -> Result<(), CliError> {
let mut s = open(io, &a.file)?;
print_range(io, &mut s, a.range.as_deref(), a.sheet.as_deref(), a.formulas, a.csv)
}
fn run(a: &RunArgs, io: &mut Io) -> Result<(), CliError> {
if let (Some(input), Some(out)) = (&a.input, &a.out) {
refuse_replace(input, out, a.overwrite)?;
}
let mut s = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
let mut step = 0usize;
for item in &a.steps {
let cmds: Vec<(String, Value, String)> = match item {
RunStep::Cmd(c) => c.iter().map(|(id, p)| (id.clone(), p.clone(), "--cmd".to_string())).collect(),
RunStep::Script(path) => {
let value = path.display().to_string();
let text = std::fs::read_to_string(path).map_err(|source| CliError::File { path: path.clone(), source })?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
let origin = format!("{value}:{}", i + 1);
if let Some((id, p)) = parse_command(line).map_err(|source| CliError::Script { origin: origin.clone(), source })? {
v.push((id, p, origin));
}
}
v
}
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(io, &mut s, &id, p).map_err(|e| CliError::Step { step, origin, id: id.clone(), message: e.to_string() })?;
if !a.quiet && !r.is_null() {
outln!(io, "{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = &a.out {
let out = unicode(out)?;
let r = exec(io, &mut s, "file.save", json!({"path": out}))?;
errln!(io, "wrote {out} ({} bytes)", r["bytes"]);
}
for range in &a.print {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(io, &mut s, range, a.sheet.as_deref(), a.formulas, a.csv)?;
}
Ok(())
}
fn commands(a: &ListArgs, io: &mut Io) -> Result<(), CliError> {
let q = a.search.as_ref().or(a.word.as_ref()).map(|q| q.to_ascii_lowercase());
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.json {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!(io, "{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!(io, "{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!(io, "{:<w$} {}", "", c.params);
}
errln!(io, "{} commands", list.len());
Ok(())
}
fn functions(a: &FunctionsArgs, io: &mut Io) -> Result<(), CliError> {
let mut p = json!({});
if let Some(q) = a.search.as_ref().or(a.word.as_ref()) {
p["search"] = json!(q);
}
if let Some(c) = &a.category {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(io, &mut s, "formulas.functions", p)?;
if a.json {
outln!(io, "{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!(io, "{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(io, " {cat}: {desc}");
}
errln!(io, "{} functions", list.len());
Ok(())
}
fn connect(port: &str) -> Result<gridcraft_mcp::Remote, CliError> {
use gridcraft_mcp::control_addr;
let addr = control_addr(port);
gridcraft_mcp::Remote::connect(&addr).map_err(|e| CliError::Connect { addr, port: port.to_owned(), message: e.to_string() })
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app started with
/// `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(a: &McpArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::{Backend, Headless, Server};
let backend: Box<dyn Backend> = match &a.connect {
Some(c) => Box::new(connect(c)?),
None => {
let session = match (&a.input, &a.sample) {
(Some(p), _) => open(io, p)?,
(None, Some(name)) => sample(io, name)?,
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
errln!(io, "gridcraft-cli: MCP server on stdio ({})", backend.describe());
// Replies go to the writer supplied to `run` (the CLI binary passes process stdout).
let stdin = std::io::stdin();
Server::new(backend).serve(stdin.lock(), &mut *io.out).map_err(CliError::engine)
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(a: &SendArgs, io: &mut Io) -> Result<(), CliError> {
use gridcraft_mcp::Backend;
let params = a.params.clone().unwrap_or_else(|| json!({}));
let mut r = connect(&a.port)?;
let v = r.call(&a.method, params).map_err(CliError::engine)?;
outln!(io, "{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = crate::run(["convert", input.to_str().unwrap(), output.to_str().unwrap()], &mut out, &mut err);
assert_eq!(code, 0, "{}", String::from_utf8_lossy(&err));
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
}
+41
View File
@@ -0,0 +1,41 @@
use std::path::{Path, PathBuf};
/// Why a command failed: printed as `error: {e}`, exit 1. The engine, the MCP backends and the sandbox report their
/// failures as text; [`CliError::Engine`] carries it.
#[derive(Debug, thiserror::Error)]
pub(crate) enum CliError {
/// What the engine, a backend or a library reported.
#[error("{0}")]
Engine(String),
/// The engine's commands take paths as JSON, which holds only text.
#[error("{}: the path is not valid Unicode", .0.display())]
NotUnicode(PathBuf),
#[error("{}: {source}", path.display())]
File { path: PathBuf, source: std::io::Error },
#[error("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)")]
OutputFormat { out: String },
#[error("{} is the workbook {}: writing it would replace the input (pass --overwrite to replace it)", out.display(), input.display())]
WouldReplace { out: PathBuf, input: PathBuf },
#[error("cannot connect to the GridCraft app at {addr}: {message} (start it with `gridcraft --control {port}`)")]
Connect { addr: String, port: String, message: String },
#[error("step {step} ({origin}, {id}): {message}")]
Step { step: usize, origin: String, id: String, message: String },
#[error("{origin}: {source}")]
Script { origin: String, source: crate::script::ScriptError },
#[error("sandbox-check: {0}")]
Sandbox(String),
/// Standard output went away.
#[error("can't write to stdout: {0}")]
Stdout(std::io::Error),
}
impl CliError {
pub(crate) fn engine(e: impl ToString) -> Self {
Self::Engine(e.to_string())
}
}
/// A path as the text the engine's commands take.
pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> {
path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned()))
}
+131
View File
@@ -0,0 +1,131 @@
//! Headless GridCraft (`gridcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
//! through the binary; `gridcraft-cli --help` lists the subcommands. The conventions are RFC-0018's: exit 0, 1 (a
//! command failed) or 2 (a usage error), results on stdout, `error: <message>` on stderr.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod args;
mod check;
mod commands;
mod error;
mod sandbox_check;
mod script;
use std::ffi::OsString;
use std::io::Write;
use error::CliError;
pub use args::command;
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
pub(crate) struct Io<'a> {
pub(crate) out: &'a mut dyn Write,
pub(crate) err: &'a mut dyn Write,
}
/// Writes a line of results; fails with [`CliError::Stdout`], which `run` turns into a quiet end for a closed pipe
/// (`gridcraft-cli commands | head`) and a message for any other error.
macro_rules! outln {
($io:expr, $($arg:tt)*) => {
writeln!($io.out, $($arg)*).map_err($crate::error::CliError::Stdout)?
};
}
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
macro_rules! errln {
($io:expr, $($arg:tt)*) => {
drop(writeln!($io.err, $($arg)*))
};
}
pub(crate) use {errln, outln};
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the tokens a shell would see
/// before `--` count: after it they are file names.
fn launch_profile_argument(args: &[OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
/// Run the CLI on its arguments (without the program name), writing results to `out` and diagnostics to `err`.
/// Returns the process exit code: 0 on success, 1 when a command failed, 2 for a usage error. Help and the version go
/// to `out`, exit 0.
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
where
I: IntoIterator<Item = T>,
T: Into<OsString>,
{
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
// A confined launcher run (and its probes) comes first, before anything else starts.
if let Some(code) = gridcraft_sandbox::handle_args(&args) {
return code;
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a CLI option, and a CLI
// that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&args) {
let _ = writeln!(err, "error: {flag} belongs to the GridCraft desktop app, not this CLI");
return 2;
}
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
let cli = match args::parse(&args) {
Ok(cli) => cli,
Err(e) if e.use_stderr() => {
// A usage diagnostic that cannot be written still returns 2.
let _ = write!(err, "{}", e.render()).and_then(|()| err.flush());
return e.exit_code();
}
Err(e) => {
// Help or the version, on stdout: a closed pipe ends quietly; any other failure is reported and returns 1.
return match write!(out, "{}", e.render()).and_then(|()| out.flush()) {
Ok(()) => e.exit_code(),
Err(w) if w.kind() == std::io::ErrorKind::BrokenPipe => e.exit_code(),
Err(w) => {
let _ = writeln!(err, "error: {}", CliError::Stdout(w));
1
}
};
}
};
let mut io = Io { out, err };
match commands::dispatch(cli.command, &mut io) {
Ok(code) => code,
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
Err(CliError::Stdout(e)) if e.kind() == std::io::ErrorKind::BrokenPipe => 0,
Err(e) => {
errln!(io, "error: {e}");
1
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2 rather than acting on
/// whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
}
+4 -705
View File
@@ -1,710 +1,9 @@
//! Headless GridCraft.
//!
//! ```text
//! gridcraft-cli info <file> [--json]
//! gridcraft-cli convert <in> <out> [--sheet NAME]
//! gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
//! gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
//! gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
//! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet]
//! gridcraft-cli commands [--json] [--search X]
//! gridcraft-cli functions [--json] [--search X] [--category C]
//! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
//! gridcraft-cli send <port> <method> [json]
//! gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
//! gridcraft-cli version | --version
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! `gridcraft-cli`: headless GridCraft. Thin wiring over [`gridcraft_cli::run`].
use std::process::ExitCode;
/// `println!` that ends the program quietly when stdout is closed (`gridcraft-cli commands |
/// head`) instead of panicking on a broken pipe.
macro_rules! outln {
($($arg:tt)*) => {{
use std::io::Write as _;
if let Err(e) = writeln!(std::io::stdout(), $($arg)*) {
$crate::stdout_failed(e);
}
}};
}
mod check;
mod sandbox_check;
use gridcraft_engine::Session;
use serde_json::{Value, json};
const USAGE: &str = "usage:
gridcraft-cli info <file> [--json] sheets, used ranges, tables, charts, names
gridcraft-cli convert <in> <out> [--sheet NAME] xlsx/csv/tsv/json/html/pdf by extension
gridcraft-cli eval <formula> [--in FILE] [--sheet S] [--cell A1] [--json]
gridcraft-cli cat <file> [--range A1:D20] [--sheet S] [--formulas] [--csv]
gridcraft-cli check <file-or-dir>... [--json] [--tolerance 1e-9] [--max-report N]
cached-value calc oracle + XLSX round-trip fidelity (exit 1 on any difference)
gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl]
[--out FILE] [--print RANGE] [--quiet]
a script line is id={json} or {\"command\": \"id\", \"params\": {…}};
blank lines and lines starting with # or // are skipped
gridcraft-cli commands [--json] [--search X]
gridcraft-cli functions [--json] [--search X] [--category C]
gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME]
gridcraft-cli send <port> <method> [json]
gridcraft-cli sandbox-check [--read PATH]... [--exec PATH]... [-- PROGRAM ARGS...]
whether this system confines programs (no program: a confined self-test)
gridcraft-cli version";
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly; any
/// other write error is reported.
fn stdout_failed(e: std::io::Error) -> ! {
if e.kind() == std::io::ErrorKind::BrokenPipe {
std::process::exit(0);
}
eprintln!("gridcraft-cli: can't write to stdout: {e}");
std::process::exit(1);
}
/// The first Launcher-profile argument in `args`, in either its separate or `=` form. Only the
/// tokens a shell would see before `--` count: after it they are file names.
fn launch_profile_argument(args: &[std::ffi::OsString]) -> Option<String> {
for arg in args {
if arg == "--" {
return None;
}
let text = arg.to_string_lossy();
for flag in ["--launch-profile", "--profile-root"] {
if text == flag || text.starts_with(&format!("{flag}=")) {
return Some(flag.to_string());
}
}
}
None
}
fn main() -> ExitCode {
// A confined launcher run (and its probes) comes first, before anything else starts.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
return ExitCode::from(u8::try_from(code).unwrap_or(1));
}
// The nightly profile protocol belongs to the desktop app: the Launcher's selector is not a
// CLI option, and a CLI that silently ignored it would act on the wrong files.
if let Some(flag) = launch_profile_argument(&raw) {
eprintln!("gridcraft-cli: {flag} belongs to the GridCraft desktop app, not this CLI");
return ExitCode::from(2);
}
let args: Vec<String> = std::env::args().skip(1).collect();
let rest = args.get(1..).unwrap_or_default();
let r = match args.first().map(String::as_str) {
Some("--version" | "-V" | "version") => {
outln!("gridcraft-cli {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some("--help" | "-h" | "help") => {
outln!("{USAGE}");
Ok(())
}
Some("info") => info(rest),
Some("convert") => convert(rest),
Some("eval") => eval(rest),
Some("cat") => cat(rest),
Some("run") => run(rest),
Some("check") => return check::main(rest),
Some("sandbox-check") => return sandbox_check::main(rest),
Some("commands") => commands(rest),
Some("functions") => functions(rest),
Some("mcp") => mcp(rest),
Some("send") => send(rest),
Some(other) => Err(format!("unknown subcommand `{other}`\n{USAGE}")),
None => Err(USAGE.to_string()),
};
match r {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("gridcraft-cli: {e}");
ExitCode::FAILURE
}
}
}
// ---------------------------------------------------------------- argument parsing
/// Parsed arguments: positionals, `--flag value` options and boolean `--switch`es.
struct Args {
positional: Vec<String>,
opts: Vec<(String, String)>,
switches: Vec<String>,
}
impl Args {
/// `with_value` lists the options that take a value; `switches` the boolean ones. Anything
/// else starting with `--` is an error.
fn parse(args: &[String], with_value: &[&str], switches: &[&str]) -> Result<Args, String> {
let mut out = Args { positional: vec![], opts: vec![], switches: vec![] };
let mut it = args.iter();
while let Some(a) = it.next() {
if let Some(name) = a.strip_prefix("--").filter(|n| !n.is_empty()) {
let (name, inline) = match name.split_once('=') {
Some((n, v)) => (n, Some(v.to_string())),
None => (name, None),
};
if with_value.contains(&name) {
let v = match inline {
Some(v) => v,
None => it.next().cloned().ok_or_else(|| format!("--{name} needs a value"))?,
};
out.opts.push((name.to_string(), v));
} else if switches.contains(&name) && inline.is_none() {
out.switches.push(name.to_string());
} else {
return Err(format!("unknown option --{name}"));
}
} else {
out.positional.push(a.clone());
}
}
Ok(out)
}
fn opt(&self, name: &str) -> Option<&str> {
self.opts.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.as_str())
}
fn has(&self, name: &str) -> bool {
self.switches.iter().any(|s| s == name)
}
fn pos(&self, i: usize, what: &str) -> Result<&str, String> {
self.positional.get(i).map(String::as_str).ok_or_else(|| format!("missing {what}\n{USAGE}"))
}
fn no_extra(&self, n: usize) -> Result<(), String> {
match self.positional.get(n) {
Some(x) => Err(format!("unexpected argument `{x}`")),
None => Ok(()),
}
}
}
// ---------------------------------------------------------------- helpers
fn exec(s: &mut Session, id: &str, params: Value) -> Result<Value, String> {
let r = s.execute_headless(id, params).map_err(|e| e.to_string());
if matches!(id, "file.open" | "file.save" | "file.saveAs" | "file.saveBytes")
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
for warning in warnings.iter().filter_map(Value::as_str) {
eprintln!("Warning: {warning}");
}
}
r
}
fn open(path: &str) -> Result<Session, String> {
let mut s = Session::new();
exec(&mut s, "file.open", json!({"path": path}))?;
Ok(s)
}
fn blank() -> Session {
let mut s = Session::new();
s.new_workbook();
s
}
fn activate_sheet(s: &mut Session, sheet: Option<&str>) -> Result<(), String> {
if let Some(name) = sheet {
let p = match name.parse::<u64>() {
// A number that isn't also a sheet name is an index.
Ok(i) if s.doc().is_ok_and(|d| d.wb.sheet_index(name).is_none()) => json!({"sheet": i}),
_ => json!({"sheet": name}),
};
exec(s, "sheet.activate", p)?;
}
Ok(())
}
fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
}
/// A number as a person would type it: `6`, `0.5`, `1e+300`.
fn number_text(n: f64) -> String {
if n.fract() == 0.0 && n.abs() < 1e15 {
format!("{}", n as i64)
} else if n.is_finite() && (n.abs() >= 1e15 || n.abs() < 1e-5) {
// Rust's `Display` never uses exponent form; `{:e}` omits the `+` on positive exponents.
let s = format!("{n:e}");
match s.split_once('e') {
Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
_ => s,
}
} else {
format!("{n}")
}
}
/// A computed value (as returned by `formulas.evaluate` / `sheet.read`) as plain text.
fn value_text(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
Value::Number(n) => n.as_f64().map(number_text).unwrap_or_else(|| n.to_string()),
Value::String(s) => s.clone(),
Value::Object(o) => o.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| v.to_string()),
Value::Array(rows) => rows
.iter()
.map(|r| match r {
Value::Array(cells) => cells.iter().map(value_text).collect::<Vec<_>>().join("\t"),
other => value_text(other),
})
.collect::<Vec<_>>()
.join("\n"),
}
}
fn csv_field(s: &str, delim: char) -> String {
if s.contains(delim) || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
// ---------------------------------------------------------------- subcommands
fn info(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &[], &["json"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
let v = exec(&mut s, "document.inspect", json!({}))?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
outln!("{}", v["title"].as_str().unwrap_or(path));
for (i, sh) in v["sheets"].as_array().into_iter().flatten().enumerate() {
let active = if v["activeSheet"].as_u64() == Some(i as u64) { "*" } else { " " };
let vis = sh["visibility"].as_str().filter(|x| *x != "Visible").map(|x| format!(" ({x})")).unwrap_or_default();
outln!(
"{active} {}{vis}: used {}, {} cells",
sh["name"].as_str().unwrap_or("?"),
sh["usedRange"].as_str().unwrap_or("(empty)"),
sh["cells"].as_u64().unwrap_or(0)
);
for t in sh["tables"].as_array().into_iter().flatten() {
outln!(" table {} {} ({})", t["name"].as_str().unwrap_or("?"), t["range"].as_str().unwrap_or("?"), t["style"].as_str().unwrap_or(""));
}
for c in sh["charts"].as_array().into_iter().flatten() {
let title = c["title"].as_str().map(|t| format!(" \"{t}\"")).unwrap_or_default();
outln!(" chart {}{title} at {}, {} series", c["kind"].as_str().unwrap_or("?"), c["at"].as_str().unwrap_or("?"), c["series"]);
}
if let Some(f) = sh["autofilter"].as_str() {
outln!(" filter {f}");
}
}
let names = v["names"].as_array().cloned().unwrap_or_default();
if !names.is_empty() {
outln!("names:");
for n in names {
outln!(" {} {}", n["name"].as_str().unwrap_or("?"), n["refersTo"].as_str().unwrap_or(""));
}
}
Ok(())
}
fn convert(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["sheet"], &[])?;
let input = a.pos(0, "<in>")?;
let out = a.pos(1, "<out>")?;
a.no_extra(2)?;
let pdf = out.to_ascii_lowercase().ends_with(".pdf");
if !pdf && gridcraft_engine::io::FileKind::from_path(out).is_none() {
return Err(format!("{out}: unknown output format (use .xlsx, .csv, .tsv, .json, .html or .pdf)"));
}
let mut s = open(input)?;
activate_sheet(&mut s, a.opt("sheet"))?;
if pdf {
let result = exec(&mut s, "file.exportPdf", json!({"path": out}))?;
eprintln!("wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
return Ok(());
}
for warning in gridcraft_engine::cmd::file::save_losses(&s, "file.save", &json!({"path": out})).messages() {
eprintln!("Warning: {warning}");
}
let d = s.doc().map_err(|e| e.to_string())?;
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(|e| e.to_string())?;
gridcraft_engine::io::write_file(out, &bytes).map_err(|e| e.to_string())?;
eprintln!("wrote {out} ({} bytes)", bytes.len());
Ok(())
}
fn eval(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sheet", "cell"], &["json"])?;
let formula = a.pos(0, "<formula>")?;
a.no_extra(1)?;
let mut s = match a.opt("in") {
Some(p) => open(p)?,
None => blank(),
};
activate_sheet(&mut s, a.opt("sheet"))?;
let formula = if formula.starts_with('=') { formula.to_string() } else { format!("={formula}") };
let mut p = json!({"formula": formula});
if let Some(c) = a.opt("cell") {
p["cell"] = json!(c);
}
let v = exec(&mut s, "formulas.evaluate", p)?;
if a.has("json") {
outln!("{}", serde_json::to_string(&v).unwrap_or_default());
} else {
outln!("{}", value_text(&v));
}
Ok(())
}
/// Prints `range` of the active (or `sheet`) sheet as an aligned table or CSV.
fn print_range(s: &mut Session, range: Option<&str>, sheet: Option<&str>, formulas: bool, csv: bool) -> Result<(), String> {
let mut p = json!({});
if let Some(r) = range {
p["range"] = json!(r);
}
if let Some(sh) = sheet {
p["sheet"] = json!(sh);
}
let raw = exec(s, "sheet.read", p.clone())?;
p["formatted"] = json!(true);
p["formulas"] = json!(formulas);
let shown = exec(s, "sheet.read", p)?;
let rows: Vec<Vec<String>> = shown["values"]
.as_array()
.into_iter()
.flatten()
.map(|r| r.as_array().into_iter().flatten().map(|c| c.as_str().map(str::to_string).unwrap_or_else(|| value_text(c))).collect())
.collect();
if csv {
for r in &rows {
outln!("{}", r.iter().map(|c| csv_field(c, ',')).collect::<Vec<_>>().join(","));
}
return Ok(());
}
let numeric = |ri: usize, ci: usize| raw["values"][ri][ci].is_number() && !formulas;
let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
let widths: Vec<usize> = (0..ncols).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|t| t.chars().count()).max().unwrap_or(0).min(60)).collect();
for (ri, r) in rows.iter().enumerate() {
let mut line = String::new();
for (ci, cell) in r.iter().enumerate() {
let w = widths.get(ci).copied().unwrap_or(0);
let cell: String = cell.chars().map(|c| if c == '\n' || c == '\t' { ' ' } else { c }).collect();
if ci > 0 {
line.push_str(" ");
}
if numeric(ri, ci) {
line.push_str(&format!("{cell:>w$}"));
} else {
line.push_str(&format!("{cell:<w$}"));
}
}
outln!("{}", line.trim_end());
}
Ok(())
}
fn cat(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["range", "sheet"], &["formulas", "csv"])?;
let path = a.pos(0, "<file>")?;
a.no_extra(1)?;
let mut s = open(path)?;
print_range(&mut s, a.opt("range"), a.opt("sheet"), a.has("formulas"), a.has("csv"))
}
/// One command from `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
fn parse_command(text: &str) -> Result<Option<(String, Value)>, String> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| format!("bad JSON: {e}"))?;
// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the
// script still exited 0, so a typo made a valid, wrong workbook (#2256).
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let (plural, list) = (if unknown.len() == 1 { "key" } else { "keys" }, unknown.join("`, `"));
return Err(format!("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}"));
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or("JSON command needs a `command` field")?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() { json!({}) } else { serde_json::from_str(rest).map_err(|e| format!("{id}: bad JSON params: {e}"))? };
Ok(Some((id.to_string(), params)))
}
fn run(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["in", "sample", "cmd", "script", "out", "print", "sheet"], &["quiet", "csv", "formulas"])?;
a.no_extra(0)?;
let mut s = match (a.opt("in"), a.opt("sample")) {
(Some(_), Some(_)) => return Err("give --in or --sample, not both".into()),
(Some(p), None) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
let quiet = a.has("quiet");
let mut step = 0usize;
for (name, value) in &a.opts {
let cmds: Vec<(String, Value, String)> = match name.as_str() {
"cmd" => parse_command(value)?.map(|(id, p)| vec![(id, p, "--cmd".to_string())]).unwrap_or_default(),
"script" => {
let text = std::fs::read_to_string(value).map_err(|e| format!("{value}: {e}"))?;
let mut v = Vec::new();
for (i, line) in text.lines().enumerate() {
if let Some((id, p)) = parse_command(line).map_err(|e| format!("{value}:{}: {e}", i + 1))? {
v.push((id, p, format!("{value}:{}", i + 1)));
}
}
v
}
_ => continue,
};
for (id, p, origin) in cmds {
step += 1;
let r = exec(&mut s, &id, p).map_err(|e| format!("step {step} ({origin}, {id}): {e}"))?;
if !quiet && !r.is_null() {
outln!("{}", serde_json::to_string(&json!({"command": id, "result": r})).unwrap_or_default());
}
}
}
if let Some(out) = a.opt("out") {
let r = exec(&mut s, "file.save", json!({"path": out}))?;
eprintln!("wrote {out} ({} bytes)", r["bytes"]);
}
for (name, range) in &a.opts {
if name == "print" {
let range = if range.is_empty() || range == "used" { None } else { Some(range.as_str()) };
print_range(&mut s, range, a.opt("sheet"), a.has("formulas"), a.has("csv"))?;
}
}
Ok(())
}
fn commands(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search"], &["json"])?;
let q = a.opt("search").or(a.positional.first().map(String::as_str)).map(str::to_ascii_lowercase);
let s = Session::new();
let list: Vec<_> = s
.commands()
.into_iter()
.filter(|c| {
q.as_ref().is_none_or(|q| {
c.id.to_ascii_lowercase().contains(q.as_str())
|| c.label.to_ascii_lowercase().contains(q.as_str())
|| c.menu.iter().any(|m| m.to_ascii_lowercase().contains(q.as_str()))
})
})
.collect();
if a.has("json") {
// Enablement depends on a live workbook; not meaningful here.
let v: Vec<Value> =
list.iter().map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params})).collect();
outln!("{}", pretty(&Value::Array(v)));
return Ok(());
}
let w = list.iter().map(|c| c.id.len()).max().unwrap_or(0);
for c in &list {
let sc = c.shortcut.map(|s| format!(" [{s}]")).unwrap_or_default();
let menu = if c.menu.is_empty() { String::new() } else { format!(" ({})", c.menu.join(" > ")) };
outln!("{:<w$} {}{menu}{sc}", c.id, c.label.trim_end_matches('…'));
outln!("{:<w$} {}", "", c.params);
}
eprintln!("{} commands", list.len());
Ok(())
}
fn functions(args: &[String]) -> Result<(), String> {
let a = Args::parse(args, &["search", "category"], &["json"])?;
let mut p = json!({});
if let Some(q) = a.opt("search").or(a.positional.first().map(String::as_str)) {
p["search"] = json!(q);
}
if let Some(c) = a.opt("category") {
p["category"] = json!(c);
}
let mut s = Session::new();
let v = exec(&mut s, "formulas.functions", p)?;
if a.has("json") {
outln!("{}", pretty(&v));
return Ok(());
}
let list = v.as_array().cloned().unwrap_or_default();
for f in &list {
let sig = f["signature"].as_str().or(f["name"].as_str()).unwrap_or("?");
outln!("{sig}");
let cat = f["category"].as_str().unwrap_or("");
let desc = f["description"].as_str().unwrap_or("");
outln!(" {cat}: {desc}");
}
eprintln!("{} functions", list.len());
Ok(())
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
/// started with `gridcraft --control PORT`). JSON-RPC on stdin/stdout; logs on stderr.
fn mcp(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Headless, Remote, Server, control_addr};
let a = Args::parse(args, &["connect", "in", "sample"], &[])?;
a.no_extra(0)?;
let backend: Box<dyn Backend> = match a.opt("connect") {
Some(c) => {
let addr = control_addr(c);
Box::new(
Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control PORT`)"))?,
)
}
None => {
let session = match (a.opt("in"), a.opt("sample")) {
(Some(p), _) => open(p)?,
(None, Some(name)) => {
let mut s = Session::new();
exec(&mut s, "file.new", json!({"sample": name}))?;
s
}
(None, None) => blank(),
};
Box::new(Headless::with_session(session))
}
};
eprintln!("gridcraft-cli: MCP server on stdio ({})", backend.describe());
let stdin = std::io::stdin();
let stdout = std::io::stdout();
Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string())
}
/// `send PORT METHOD [JSON]`: one control-channel request to a running app.
fn send(args: &[String]) -> Result<(), String> {
use gridcraft_mcp::{Backend, Remote, control_addr};
let port = args.first().ok_or_else(|| format!("missing <port>\n{USAGE}"))?;
let method = args.get(1).ok_or_else(|| format!("missing <method>\n{USAGE}"))?;
let params: Value = match args.get(2) {
Some(t) => serde_json::from_str(t).map_err(|e| format!("bad JSON params: {e}"))?,
None => json!({}),
};
if let Some(x) = args.get(3) {
return Err(format!("unexpected argument `{x}`"));
}
let addr = control_addr(port);
let mut r = Remote::connect(&addr)
.map_err(|e| format!("cannot connect to the GridCraft app at {addr}: {e} (start it with `gridcraft --control {port}`)"))?;
let v = r.call(method, params)?;
outln!("{}", pretty(&v));
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
/// The Launcher's nightly selector belongs to the desktop app; the CLI says so and exits 2
/// rather than acting on whatever it thinks the file list is.
#[test]
fn launcher_profile_arguments_are_refused_in_both_forms_and_only_before_the_delimiter() {
let args = |values: &[&str]| values.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
assert_eq!(launch_profile_argument(&args(&["--launch-profile", "nightly-v1"])).as_deref(), Some("--launch-profile"));
assert_eq!(launch_profile_argument(&args(&["--profile-root", "/tmp/p", "info", "a.xlsx"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["--profile-root=/tmp/p"])).as_deref(), Some("--profile-root"));
assert_eq!(launch_profile_argument(&args(&["info", "--launch-profile=nightly-v1"])).as_deref(), Some("--launch-profile"));
// After `--` they are file names, exactly as the desktop app parses them.
assert_eq!(launch_profile_argument(&args(&["--", "--launch-profile", "nightly-v1"])), None);
assert_eq!(launch_profile_argument(&args(&["--", "--profile-root=/tmp/p"])), None);
assert_eq!(launch_profile_argument(&args(&["info", "a.xlsx", "--json"])), None);
assert_eq!(launch_profile_argument(&[]), None);
}
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused");
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused");
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
#[test]
fn value_texts() {
assert_eq!(value_text(&json!(6.0)), "6");
assert_eq!(value_text(&json!(0.25)), "0.25");
assert_eq!(value_text(&json!(1e300)), "1e+300");
assert_eq!(value_text(&json!(-1.5e300)), "-1.5e+300");
assert_eq!(value_text(&json!(1e-20)), "1e-20");
assert_eq!(value_text(&json!(1e-300)), "1e-300");
assert_eq!(value_text(&json!(0.0001)), "0.0001");
assert_eq!(value_text(&json!(true)), "TRUE");
assert_eq!(value_text(&json!({"error": "#DIV/0!"})), "#DIV/0!");
assert_eq!(value_text(&json!([[1.0, 2.0], [3.0, "x"]])), "1\t2\n3\tx");
}
#[test]
fn args_parsing() {
let v: Vec<String> = ["a", "--range", "A1", "--csv", "--sheet=S"].iter().map(|s| s.to_string()).collect();
let a = Args::parse(&v, &["range", "sheet"], &["csv"]).unwrap();
assert_eq!(a.positional, ["a"]);
assert_eq!(a.opt("range"), Some("A1"));
assert_eq!(a.opt("sheet"), Some("S"));
assert!(a.has("csv"));
assert!(Args::parse(&["--nope".to_string()], &[], &[]).is_err());
assert!(Args::parse(&["--range".to_string()], &["range"], &[]).is_err());
}
#[test]
fn convert_xlsx_to_pdf_keeps_links() {
let dir = std::env::temp_dir().join(format!("gridcraft-cli-pdf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let input = dir.join("links.xlsx");
let output = dir.join("links.pdf");
let mut s = blank();
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
let bytes = gridcraft_engine::io::save_file_bytes(&s.doc().unwrap().wb, input.to_str().unwrap()).unwrap();
gridcraft_engine::io::write_file(input.to_str().unwrap(), &bytes).unwrap();
convert(&[input.to_string_lossy().into_owned(), output.to_string_lossy().into_owned()]).unwrap();
let pdf = std::fs::read(&output).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
assert!(pdf.windows(b"/URI (https://example.org)".len()).any(|w| w == b"/URI (https://example.org)"));
std::fs::remove_dir_all(dir).unwrap();
}
let (mut out, mut err) = (std::io::stdout().lock(), std::io::stderr().lock());
// An exit code is 0 to 2 here; 128 + signal is the shell's, for a process a signal ended.
ExitCode::from(u8::try_from(gridcraft_cli::run(std::env::args_os().skip(1), &mut out, &mut err)).unwrap_or(1))
}
+58 -46
View File
@@ -12,87 +12,99 @@
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;
use crate::args::SandboxCheckArgs;
use crate::error::CliError;
use crate::{Io, errln, outln};
use gridcraft_sandbox::{Canary, Policy, REFUSED_EXIT_CODE, REPORT_FLAG, Support};
pub fn main(args: &[String]) -> ExitCode {
match run(args) {
Ok(code) => code,
Err(e) => {
eprintln!("gridcraft-cli: sandbox-check: {e}");
ExitCode::FAILURE
}
}
}
fn run(args: &[String]) -> Result<ExitCode, String> {
pub(crate) fn run(a: &SandboxCheckArgs, io: &mut Io) -> Result<i32, CliError> {
let mut policy = Policy::new().with_system_libraries();
let mut it = args.iter();
let mut program: Option<(PathBuf, Vec<OsString>)> = None;
while let Some(a) = it.next() {
match a.as_str() {
"--read" => policy = policy.read(it.next().ok_or("--read needs a path")?),
"--exec" => policy = policy.exec(it.next().ok_or("--exec needs a path")?),
"--" => {
let p = it.next().ok_or("a program follows `--`")?;
program = Some((PathBuf::from(p), it.by_ref().map(OsString::from).collect()));
}
other => return Err(format!("unknown option `{other}`")),
}
for path in &a.read {
policy = policy.read(path);
}
for path in &a.exec {
policy = policy.exec(path);
}
let program: Option<(PathBuf, Vec<OsString>)> = a.program.split_first().map(|(p, rest)| (PathBuf::from(p), rest.to_vec()));
// With a program, its standard output is passed through untouched, so this command's own
// lines go to standard error; the self-test's report is the output, on standard output.
let report = program.is_none();
let say = |line: String| {
let say = |io: &mut Io, line: String| -> Result<(), CliError> {
if report {
outln!("{line}");
outln!(io, "{line}");
} else {
eprintln!("{line}");
errln!(io, "{line}");
}
Ok(())
};
match gridcraft_sandbox::support() {
Support::Available(how) => say(format!("sandbox: available ({how})")),
Support::Available(how) => say(io, format!("sandbox: available ({how})"))?,
Support::Unsupported(why) => {
say(format!("sandbox: unsupported ({why})"));
return Ok(ExitCode::from(2));
say(io, format!("sandbox: unsupported ({why})"))?;
return Ok(2);
}
}
let canary = Canary::create().map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let canary = Canary::create().map_err(|e| CliError::Sandbox(e.to_string()))?;
let exe = std::env::current_exe().map_err(|e| CliError::Sandbox(e.to_string()))?;
let (program, program_args) = match program {
Some((p, a)) => (p, a),
// A confined copy of this program, reporting each attempt; it reads its own executable as
// the allowed file.
None => {
// The self-test re-runs this executable with REPORT_FLAG. That only works when this
// process is the gridcraft-cli binary (its `main` calls `handle_args` first). A host
// that only called `run` — a test binary, for example — would not run the probes.
if !is_gridcraft_cli_binary(&exe) {
return Err(CliError::Sandbox(
"the self-test must be run through the gridcraft-cli binary (pass a program after `--` to confine one from any host)".into(),
));
}
let home = std::env::var_os("HOME").unwrap_or_default();
(exe.clone(), vec![REPORT_FLAG.into(), canary.file().into(), exe.clone().into(), home])
}
};
let policy = policy.exec(program.clone());
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| e.to_string())?;
let status = cmd.status().map_err(|e| format!("couldn't start the launcher: {e}"))?;
let mut cmd = gridcraft_sandbox::launch_command(&policy, &canary, &program, &program_args).map_err(|e| CliError::Sandbox(e.to_string()))?;
let status = cmd.status().map_err(|e| CliError::Sandbox(format!("couldn't start the launcher: {e}")))?;
drop(canary);
match status.code() {
Some(0) => {
say(if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into());
Ok(ExitCode::SUCCESS)
say(
io,
if report { "result: every attempt is as the sandbox requires" } else { "result: the program ran confined and succeeded" }.into(),
)?;
Ok(0)
}
Some(REFUSED_EXIT_CODE) => {
// The launcher's refusal and a program's own exit share the code; the launcher's reason,
// when it refused, is the `gridcraft-sandbox: refused:` line above.
say(format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
));
Ok(ExitCode::FAILURE)
say(
io,
format!(
"result: exit code {REFUSED_EXIT_CODE}: the launcher refused to run the program (its reason is above), or the program itself exited with {REFUSED_EXIT_CODE}"
),
)?;
Ok(1)
}
other => {
say(format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
));
Ok(ExitCode::FAILURE)
say(
io,
format!(
"result: {} ({})",
if report { "some attempts are not as the sandbox requires" } else { "the program failed" },
other.map_or("no exit code".into(), |c| format!("exit code {c}"))
),
)?;
Ok(1)
}
}
}
/// The installed CLI, including the nightly package's renamed command.
fn is_gridcraft_cli_binary(exe: &std::path::Path) -> bool {
exe.file_name()
.and_then(|n| n.to_str())
.map(|n| n.strip_suffix(".exe").unwrap_or(n))
.is_some_and(|n| n == "gridcraft-cli" || n == "gridcraft-nightly-cli")
}
+92
View File
@@ -0,0 +1,92 @@
//! One command of a script: `id={json}`, `id {json}`, `id` or `{"command": id, "params": {..}}`.
use serde_json::{Value, json};
/// A command line that cannot be read.
#[derive(Debug, PartialEq, thiserror::Error)]
pub(crate) enum ScriptError {
#[error("bad JSON: {0}")]
BadJson(String),
/// A key this does not read is a mistake, not a comment: `{"command": …, "args": {…}}` and
/// `{"command": …, "name": "Report"}` ran the command with no parameters at all and the script still exited 0, so a
/// typo made a valid, wrong workbook (#2256).
#[error("unknown {plural} `{list}`: a line is {{\"command\": \"id\", \"params\": {{…}}}}")]
UnknownKeys { plural: &'static str, list: String },
#[error("JSON command needs a `command` field")]
NoCommand,
#[error("{id}: bad JSON params: {why}")]
BadParams { id: String, why: String },
}
/// A command and its parameters.
pub(crate) type Step = (String, Value);
/// The command in `text`, or `None` for a blank line, a `#` comment or a `//` comment.
pub(crate) fn parse_command(text: &str) -> Result<Option<Step>, ScriptError> {
let t = text.trim();
if t.is_empty() || t.starts_with('#') || t.starts_with("//") {
return Ok(None);
}
if t.starts_with('{') {
let v: Value = serde_json::from_str(t).map_err(|e| ScriptError::BadJson(e.to_string()))?;
if let Some(o) = v.as_object() {
let mut unknown: Vec<&str> = o.keys().map(String::as_str).filter(|k| !matches!(*k, "command" | "id" | "params")).collect();
if !unknown.is_empty() {
unknown.sort_unstable();
let plural = if unknown.len() == 1 { "key" } else { "keys" };
return Err(ScriptError::UnknownKeys { plural, list: unknown.join("`, `") });
}
}
let id = v.get("command").or_else(|| v.get("id")).and_then(Value::as_str).ok_or(ScriptError::NoCommand)?;
return Ok(Some((id.to_string(), v.get("params").cloned().unwrap_or_else(|| json!({})))));
}
let split = t.find(['=', ' ', '\t']);
let (id, rest) = match split {
Some(i) => (t.get(..i).unwrap_or(t), t.get(i + 1..).unwrap_or("").trim()),
None => (t, ""),
};
let params = if rest.is_empty() {
json!({})
} else {
serde_json::from_str(rest).map_err(|e| ScriptError::BadParams { id: id.to_string(), why: e.to_string() })?
};
Ok(Some((id.to_string(), params)))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn parses_commands() {
assert_eq!(parse_command("home.bold={\"range\":\"A1\"}").unwrap(), Some(("home.bold".into(), json!({"range": "A1"}))));
assert_eq!(parse_command("edit.undo").unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command("cell.set {\"cell\":\"A1\",\"input\":\"=1\"}").unwrap(),
Some(("cell.set".into(), json!({"cell": "A1", "input": "=1"})))
);
assert_eq!(parse_command("{\"command\":\"edit.redo\"}").unwrap(), Some(("edit.redo".into(), json!({}))));
assert_eq!(parse_command(" # comment").unwrap(), None);
assert!(parse_command("x={bad").is_err());
// A key this does not read is a mistake: the command used to run with no parameters and
// the script still exited 0, so a typo made a valid, wrong workbook (#2256).
for (line, named) in [
(r#"{"command":"home.insertSheet","args":{"name":"R"}}"#, "`args`"),
(r#"{"command":"home.insertSheet","name":"R"}"#, "`name`"),
(r#"{"command":"home.insertSheet","params":{},"note":"why"}"#, "`note`"),
] {
let e = parse_command(line).expect_err("refused").to_string();
assert!(e.contains("unknown key") && e.contains(named), "{line}: {e}");
assert!(e.contains(r#"{"command": "id", "params": {…}}"#), "{line}: {e}");
}
// Several at once are listed in one message, sorted.
let e = parse_command(r#"{"command":"x","name":"R","args":{}}"#).expect_err("refused").to_string();
assert!(e.contains("unknown keys `args`, `name`"), "{e}");
// `id` is still the accepted alternative to `command`, and `params` still carries them.
assert_eq!(parse_command(r#"{"id":"edit.undo"}"#).unwrap(), Some(("edit.undo".into(), json!({}))));
assert_eq!(
parse_command(r#"{"command":"home.insertSheet","params":{"name":"R"}}"#).unwrap(),
Some(("home.insertSheet".into(), json!({"name": "R"})))
);
}
}
+147
View File
@@ -0,0 +1,147 @@
//! What the command line does with its arguments: RFC-0018's contract, through the binary. A usage error exits 2 on
//! stderr; help and the version go to stdout with exit 0; an unknown or repeated flag after a subcommand is refused.
use std::process::Command;
struct Ran {
code: Option<i32>,
out: String,
err: String,
}
fn run(args: &[&str]) -> Ran {
let o = Command::new(env!("CARGO_BIN_EXE_gridcraft-cli")).args(args).output().unwrap();
Ran { code: o.status.code(), out: String::from_utf8_lossy(&o.stdout).into_owned(), err: String::from_utf8_lossy(&o.stderr).into_owned() }
}
const SUBCOMMANDS: [&str; 11] = ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"];
/// A usage error: exit 2, nothing on stdout, `error:` and the offending argument on stderr.
fn usage_error(args: &[&str], names: &str) {
let r = run(args);
assert_eq!(r.code, Some(2), "{args:?}: {:?} / {:?}", r.out, r.err);
assert_eq!(r.out, "", "{args:?}");
assert!(r.err.starts_with("error:") && r.err.contains(names), "{args:?}: {:?}", r.err);
}
#[test]
fn every_subcommand_answers_help_and_version_on_stdout() {
for sub in SUBCOMMANDS {
for flag in ["--help", "-h"] {
let r = run(&[sub, flag]);
assert_eq!((r.code, r.err.as_str()), (Some(0), ""), "{sub} {flag}");
assert!(r.out.contains(&format!("Usage: gridcraft-cli {sub}")), "{sub} {flag}: {:?}", r.out);
assert!(r.out.contains("Exit status:"), "{sub} {flag}: {:?}", r.out);
}
let r = run(&[sub, "--version"]);
assert_eq!((r.code, r.err.as_str()), (Some(0), ""), "{sub} --version");
assert!(r.out.starts_with(&format!("gridcraft-cli-{sub} ")), "{sub}: {:?}", r.out);
}
let r = run(&["help", "run"]);
assert_eq!(r.code, Some(0));
}
#[test]
fn an_unknown_option_is_refused_by_name_in_every_subcommand() {
for sub in ["info", "convert", "eval", "cat", "check", "run", "commands", "functions", "mcp", "send", "sandbox-check"] {
usage_error(&[sub, "--no-such-option"], "--no-such-option");
}
// An option of another subcommand is not this one's.
usage_error(&["commands", "--sample", "x"], "--sample");
usage_error(&["info", "a.xlsx", "--csv"], "--csv");
usage_error(&["cat", "a.xlsx", "--json"], "--json");
}
#[test]
fn a_missing_or_extra_argument_is_a_usage_error() {
usage_error(&["info"], "FILE");
usage_error(&["info", "a", "b"], "b");
usage_error(&["convert", "a.xlsx"], "OUTPUT");
usage_error(&["eval"], "FORMULA");
usage_error(&["check"], "FILE_OR_DIR");
usage_error(&["send", "7979"], "METHOD");
usage_error(&["run", "--in"], "--in");
usage_error(&["run", "--cmd"], "--cmd");
usage_error(&["commands", "a", "b"], "b");
}
#[test]
fn a_repeated_single_value_flag_is_refused() {
usage_error(&["convert", "a.xlsx", "b.csv", "--sheet", "1", "--sheet", "2"], "--sheet");
usage_error(&["run", "--in", "a.xlsx", "--in", "b.xlsx"], "--in");
usage_error(&["run", "--out", "a.xlsx", "--out", "b.xlsx"], "--out");
usage_error(&["check", "x.xlsx", "--tolerance", "1", "--tolerance", "2"], "--tolerance");
}
#[test]
fn conflicting_flags_are_refused_before_anything_starts() {
usage_error(&["run", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["mcp", "--connect", "7979", "--in", "a.xlsx"], "--connect");
usage_error(&["mcp", "--connect", "7979", "--sample", "sales"], "--connect");
usage_error(&["mcp", "--in", "a.xlsx", "--sample", "sales"], "--sample");
usage_error(&["commands", "x", "--search", "y"], "--search");
// `--print` carries the options that shape it.
usage_error(&["run", "--csv"], "--print");
usage_error(&["run", "--sheet", "1"], "--print");
}
#[test]
fn a_value_that_cannot_mean_anything_is_a_usage_error() {
usage_error(&["check", "x.xlsx", "--tolerance", "-1"], "--tolerance");
usage_error(&["check", "x.xlsx", "--tolerance", "nan"], "--tolerance");
usage_error(&["check", "x.xlsx", "--max-report", "many"], "--max-report");
usage_error(&["run", "--cmd", "x={bad"], "--cmd");
usage_error(&["send", "7979", "m", "{bad"], "JSON");
}
/// `eval` takes its formula as the first thing, even one that starts with a dash; `--` ends the options.
#[test]
fn a_formula_may_start_with_a_dash() {
let r = run(&["eval", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2"), "{:?}", r.err);
let r = run(&["eval", "--json", "-1+3"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "2.0"), "{:?}", r.err);
// A mistyped option is not a formula; `=` makes it one.
usage_error(&["eval", "--no-such-option"], "--no-such-option");
assert_eq!(run(&["eval", "=--1"]).code, Some(0));
// After `--`, a formula that starts with `--` is a positional value, not an option.
let r = run(&["eval", "--", "--1"]);
assert_eq!((r.code, r.out.trim()), (Some(0), "1"), "{:?}", r.err);
usage_error(&["sandbox-check", "--"], "--");
}
/// A word after the options (or after `--`) is a filter; `--search` is the same filter as an option.
#[test]
fn commands_and_functions_filter_by_a_word_or_search() {
let a = run(&["commands", "--json", "home.bold"]);
let b = run(&["commands", "--json", "--search", "home.bold"]);
assert_eq!((a.code, b.code), (Some(0), Some(0)));
assert_eq!(a.out, b.out);
assert!(a.out.contains("home.bold"));
let r = run(&["functions", "--json", "--category", "Math and trigonometry", "SUM"]);
assert_eq!(r.code, Some(0), "{}", r.err);
}
/// A failed command is exit 1 with `error:`; connection failures are command failures, not usage errors.
#[test]
fn a_failed_command_exits_1_with_an_error_line() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port().to_string();
drop(listener);
for args in [&["send", &port, "x"][..], &["mcp", "--connect", &port], &["info", "/no/such/file.xlsx"], &["convert", "/no/such.xlsx", "o.csv"]] {
let r = run(args);
assert_eq!(r.code, Some(1), "{args:?}: {:?}", r.err);
assert_eq!(r.out, "");
assert!(r.err.starts_with("error:"), "{args:?}: {:?}", r.err);
}
}
/// The nightly profile protocol belongs to the desktop app: exit 2 before any subcommand parses it.
#[test]
fn the_launcher_profile_arguments_are_refused() {
for args in [&["--launch-profile", "nightly-v1", "info", "a.xlsx"][..], &["info", "--profile-root=/tmp/x", "a.xlsx"]] {
let r = run(args);
assert_eq!((r.code, r.out.as_str()), (Some(2), ""), "{args:?}");
assert!(r.err.contains("desktop app"), "{:?}", r.err);
}
}
+12 -6
View File
@@ -25,12 +25,18 @@ fn tmpdir(name: &str) -> PathBuf {
#[test]
fn version_and_usage() {
assert_eq!(ok(&["--version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
assert_eq!(ok(&["version"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
let o = run(&["frobnicate"]);
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown subcommand"));
assert_eq!(ok(&["-V"]).trim(), format!("gridcraft-cli {}", env!("CARGO_PKG_VERSION")));
// `--version` reaches the subcommands, and there is no `version` subcommand.
assert!(ok(&["run", "--version"]).starts_with("gridcraft-cli-run "));
for unknown in ["frobnicate", "version"] {
let o = run(&[unknown]);
assert_eq!(o.status.code(), Some(2), "{unknown}");
assert!(String::from_utf8_lossy(&o.stderr).contains("unrecognized subcommand"));
}
// No arguments: the usage on stderr, a usage error.
let o = run(&[]);
assert!(!o.status.success());
assert_eq!(o.status.code(), Some(2));
assert!(o.stdout.is_empty() && String::from_utf8_lossy(&o.stderr).contains("Usage: gridcraft-cli"));
}
#[test]
@@ -275,7 +281,7 @@ fn a_script_line_with_an_unknown_key_stops_the_run() {
assert!(!info.contains("Sheet2"), "and no sheet was added with a default name: {info}");
// The usage text says what a line looks like, which is how this was found.
let usage = String::from_utf8_lossy(&run(&[]).stderr).into_owned() + &String::from_utf8_lossy(&run(&["--help"]).stdout);
let usage = ok(&["run", "--help"]);
assert!(usage.contains(r#"{"command": "id", "params": {…}}"#), "{usage}");
let _ = std::fs::remove_dir_all(&dir);
+188
View File
@@ -0,0 +1,188 @@
//! `gridcraft_cli::run` called in-process: the same program the binary is, with its streams captured, so the whole of
//! RFC-0018's surface is covered without a subprocess per case.
fn run(args: &[&str]) -> (i32, String, String) {
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = gridcraft_cli::run(args.iter().copied(), &mut out, &mut err);
(code, String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap())
}
struct Dir(std::path::PathBuf);
impl Dir {
fn new(name: &str) -> Dir {
let dir = std::env::temp_dir().join(format!("gc-inproc-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Dir(dir)
}
fn file(&self, name: &str) -> String {
self.0.join(name).to_str().unwrap().to_owned()
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn help_and_version_exit_0_on_stdout_and_usage_errors_exit_2_on_stderr() {
for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"], &["run", "-V"], &["check", "--help"]] {
let (code, out, err) = run(args);
assert_eq!((code, err.as_str()), (0, ""), "{args:?}");
assert!(!out.is_empty(), "{args:?}");
}
for args in [&[][..], &["bogus"], &["info"], &["run", "--nope"], &["info", "--bogus"]] {
let (code, out, err) = run(args);
assert_eq!((code, out.as_str()), (2, ""), "{args:?}");
assert!(err.contains("Usage: gridcraft-cli"), "{args:?}: {err}");
}
}
#[test]
fn eval_info_cat_and_commands_write_results_to_stdout_and_progress_to_stderr() {
let dir = Dir::new("flow");
let book = dir.file("b.xlsx");
let (code, out, err) = run(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("cell.set") && err.contains("wrote"), "{out} / {err}");
let (code, out, _) = run(&["eval", "=SUM(1,2,3)"]);
assert_eq!((code, out.trim()), (0, "6"));
let (code, out, err) = run(&["info", &book]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("Sheet1"), "{out}");
let (code, out, _) = run(&["info", "--json", &book]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, out, _) = run(&["cat", &book, "--csv"]);
assert_eq!((code, out.trim()), (0, "2"));
let (code, out, _) = run(&["cat", &book, "--formulas"]);
assert_eq!((code, out.trim()), (0, "=1+1"));
let csv = dir.file("b.csv");
let (code, _, err) = run(&["convert", &book, &csv]);
assert_eq!(code, 0, "{err}");
assert_eq!(std::fs::read_to_string(&csv).unwrap().trim(), "2");
let (code, _, err) = run(&["convert", &book, &dir.file("b.nope")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:") && err.contains("unknown output format"), "{err}");
}
#[test]
fn run_keeps_cmd_and_script_in_the_order_given() {
let dir = Dir::new("order");
let script = dir.file("s.jsonl");
std::fs::write(&script, "cell.set={\"cell\":\"A1\",\"input\":\"2\"}\n").unwrap();
// The script writes A1 = 2 after the first --cmd wrote 1 and before the last wrote 3: the last one wins.
let (code, out, err) = run(&[
"run",
"--quiet",
"--cmd",
r#"cell.set={"cell":"A1","input":"1"}"#,
"--script",
&script,
"--cmd",
r#"cell.set={"cell":"B1","input":"=A1*10"}"#,
"--print",
"A1:B1",
"--csv",
]);
assert_eq!(code, 0, "{err}");
assert_eq!(out.trim(), "2,20", "{out}");
let (code, _, err) = run(&["run", "--script", &dir.file("missing.jsonl")]);
assert_eq!(code, 1);
assert!(err.starts_with("error:"), "{err}");
let (code, _, err) = run(&["run", "--cmd", "no.such.command"]);
assert_eq!(code, 1);
assert!(err.contains("step 1 (--cmd, no.such.command)"), "{err}");
}
#[test]
fn check_reports_and_exits_with_the_verdict() {
let dir = Dir::new("check");
let book = dir.file("b.xlsx");
assert_eq!(run(&["run", "--quiet", "--cmd", r#"cell.set={"cell":"A1","input":"=1+1"}"#, "--out", &book]).0, 0);
let (code, out, _) = run(&["check", &book]);
assert_eq!(code, 0, "{out}");
assert!(out.contains("files: 1"), "{out}");
let (code, out, _) = run(&["check", "--json", &book, "--tolerance", "1e-6", "--max-report", "3"]);
assert_eq!(code, 0);
assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
let (code, _, _) = run(&["check", &dir.file("missing.xlsx")]);
assert_eq!(code, 1);
}
#[test]
fn sandbox_check_without_a_program_reports_on_stdout() {
// In-process `run` is not the CLI binary, so the no-program self-test is refused. The real
// verdict is asserted in `tests/it/sandbox.rs` through `CARGO_BIN_EXE_gridcraft-cli`.
let (code, out, err) = run(&["sandbox-check"]);
assert_eq!((code, out.as_str()), (1, ""), "{err}");
assert!(err.contains("error:") && err.contains("gridcraft-cli binary"), "{err}");
}
/// A closed stdout (`gridcraft-cli commands | head`) ends the program quietly; any other write error is reported.
#[test]
fn a_closed_pipe_ends_quietly_and_another_write_error_is_an_error() {
struct Failing(std::io::ErrorKind);
impl std::io::Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut err = Vec::new();
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::BrokenPipe), &mut err), 0);
assert!(err.is_empty());
assert_eq!(gridcraft_cli::run(["commands"], &mut Failing(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8(err).unwrap().starts_with("error:"));
}
/// `convert` and `run --out` refuse to replace the input without `--overwrite`.
#[test]
fn convert_and_run_refuse_to_replace_the_input() {
let dir = Dir::new("replace");
let book = dir.file("book.xlsx");
let (code, _, err) = run(&["run", "--cmd", r#"cell.set={"cell":"A1","input":"1"}"#, "--out", &book]);
assert_eq!(code, 0, "{err}");
let before = std::fs::read(&book).unwrap();
let (code, out, err) = run(&["convert", &book, &book]);
assert_eq!((code, out.as_str()), (1, ""), "{err}");
assert!(err.contains("would replace") || err.contains("--overwrite"), "{err}");
assert_eq!(std::fs::read(&book).unwrap(), before);
let (code, out, err) = run(&["run", "--in", &book, "--cmd", r#"cell.set={"cell":"A1","input":"9"}"#, "--out", &book]);
assert_eq!((code, out.as_str()), (1, ""), "{err}");
assert!(err.contains("would replace") || err.contains("--overwrite"), "{err}");
assert_eq!(std::fs::read(&book).unwrap(), before);
let (code, _, err) = run(&["run", "--in", &book, "--cmd", r#"cell.set={"cell":"A1","input":"9"}"#, "--out", &book, "--overwrite"]);
assert_eq!(code, 0, "{err}");
}
/// A StorageFull write of `--help` is reported and returns 1; a usage write failure still returns 2.
#[test]
fn help_write_failures_other_than_a_closed_pipe_return_1() {
struct Failing(std::io::ErrorKind);
impl std::io::Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(self.0.into())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut err = Vec::new();
assert_eq!(gridcraft_cli::run(["--help"], &mut Failing(std::io::ErrorKind::BrokenPipe), &mut err), 0);
assert!(err.is_empty());
err.clear();
assert_eq!(gridcraft_cli::run(["--help"], &mut Failing(std::io::ErrorKind::StorageFull), &mut err), 1);
assert!(String::from_utf8(err.clone()).unwrap().starts_with("error:"));
err.clear();
let mut out = Vec::new();
assert_eq!(gridcraft_cli::run(["eval"], &mut out, &mut Failing(std::io::ErrorKind::StorageFull)), 2);
}
+3
View File
@@ -1,4 +1,7 @@
//! The crate's integration tests, one module per file, built as one test binary.
mod args;
mod cli;
mod in_process;
mod man_and_completions;
mod sandbox;
mod text_to_columns_quotes;
@@ -0,0 +1,55 @@
//! The clap definition is consistent, and every shell's completions and every man page
//! (`examples/man-and-completions.rs`) can be generated from it.
use clap::ValueEnum;
use clap_complete::Shell;
// The example itself, so the test writes the files exactly as the packages get them.
#[allow(dead_code)]
#[path = "../../examples/man-and-completions.rs"]
mod example;
#[test]
fn command_is_consistent() {
gridcraft_cli::command().debug_assert();
}
#[test]
fn completions_generate_for_every_shell() {
for &shell in Shell::value_variants() {
let mut out = Vec::new();
clap_complete::generate(shell, &mut gridcraft_cli::command(), "gridcraft-cli", &mut out);
assert!(!out.is_empty(), "{shell}");
}
}
#[test]
fn man_pages_render_for_the_command_and_every_subcommand() {
let cmd = gridcraft_cli::command();
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
let mut out = Vec::new();
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
assert!(!out.is_empty(), "{}", page.get_name());
}
}
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
/// `packaging/freebsd/package.sh` install, `gridcraft-cli.1` and a page per subcommand, and no
/// pages for the `help` subcommand.
#[test]
fn the_example_writes_the_files_the_packages_install() {
let dir = std::env::temp_dir().join(format!("gc-cli-{}-man-and-completions", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
example::generate(&dir).unwrap();
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
written.sort();
let completions = ["gridcraft-cli.bash", "_gridcraft-cli", "gridcraft-cli.fish", "gridcraft-cli.elv", "_gridcraft-cli.ps1"];
let subcommands = ["cat", "check", "commands", "convert", "eval", "functions", "info", "mcp", "run", "sandbox-check", "send"];
let mut expected: Vec<String> = completions.map(String::from).into();
expected.push("gridcraft-cli.1".into());
expected.extend(subcommands.iter().map(|s| format!("gridcraft-cli-{s}.1")));
expected.sort();
assert_eq!(written, expected);
std::fs::remove_dir_all(&dir).unwrap();
}
-5
View File
@@ -119,11 +119,6 @@ sync_github_name = true
[people.RockerHX]
sync_github_name = true
[people.switch87]
real_name = "Gert Pellin"
display_name = "Gert Pellin"
sync_github_name = false
[people.gmrmad1]
real_name = "Madhav Agarwal"
-5
View File
@@ -141,11 +141,6 @@ 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> {
-64
View File
@@ -915,70 +915,6 @@ 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>) {
+12 -55
View File
@@ -57,9 +57,6 @@ 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
@@ -117,8 +114,6 @@ 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(),
@@ -243,25 +238,6 @@ 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).
@@ -633,10 +609,6 @@ 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
@@ -726,7 +698,18 @@ impl Host for PassHost<'_> {
}
// Spilled values sit between the stored cells (and the formulas just calculated may have
// produced some): leave such blocks to `range_values`.
if self.range_has_spill(sheet, range) {
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 {
return false;
}
for (c, cell) in sh.cells.iter_range(range) {
@@ -737,32 +720,6 @@ 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.
-19
View File
@@ -810,7 +810,6 @@ fn arrays_do_not_spill_in_tables() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
t.set("C4", "=SEQUENCE(2)");
t.set("E1", "=SEQUENCE(4)");
@@ -840,7 +839,6 @@ fn one_value_array_in_a_table_is_not_a_spill() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
};
let mut t = T::new();
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
@@ -1571,7 +1569,6 @@ fn subtotal_skips_filtered_rows() {
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
}],
style: String::new(),
@@ -1583,7 +1580,6 @@ fn subtotal_skips_filtered_rows() {
filter: crit(),
table_type: None,
connection_id: None,
query_table: None,
});
sh.autofilter = Some(AutoFilter { range: gridcraft_core::RangeRef::parse("C1:C7").unwrap(), criteria: crit() });
// Rows 3 and 5 are filtered out; row 9 (outside both filters) is hidden by hand.
@@ -2501,21 +2497,6 @@ 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
+2 -9
View File
@@ -95,15 +95,8 @@ impl Evaluator<'_> {
if (h as u64) * (w as u64) > MAX_CELLS {
return Err(CellError::Num);
}
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 values = self.host.range_values(a.sheet, part);
let ((r0, r1), (c0, c1)) = 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);
+1 -1
View File
@@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
pub use axis::{Scale, format_number, nice_scale};
pub use raster::rasterize;
pub use render::{ChartLabels, Swatch, legend_entries, legend_entries_with, render, render_with_labels, supports_trendline};
pub use render::{Swatch, legend_entries, render, supports_trendline};
pub use resolve::{default_palette, has_volatile_series, resolve, series_color};
pub use sparkline::render_sparkline;
+5 -11
View File
@@ -20,9 +20,9 @@ mod trend;
use cartesian::{cartesian, scatter};
use frame::{Bx, axis_titles, chart_title};
use kinds::{box_whisker, doughnut, funnel, histogram, pareto, pie, radar, stock, treemap, waterfall};
use kinds::{box_whisker, doughnut, funnel, histogram, pie, radar, stock, treemap, waterfall};
use legend::draw_legend;
pub use legend::{ChartLabels, Swatch, legend_entries, legend_entries_with};
pub use legend::{Swatch, legend_entries};
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).
pub(crate) const MAX_LINE_PTS: usize = 2000;
const MAX_LINE_PTS: usize = 2000;
/// Most markers per series (after de-duplicating by pixel).
pub(crate) const MAX_MARKERS: usize = 5000;
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,11 +217,6 @@ 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![];
}
@@ -238,7 +233,7 @@ pub fn render_with_labels(chart: &Chart, data: &ChartData, w: f32, h: f32, m: &d
area.y += used;
area.h -= used;
}
let entries = legend_entries_with(chart, &data, labels);
let entries = legend_entries(chart, &data);
if !entries.is_empty() && area.ok() {
area = draw_legend(&mut ctx, &entries, chart.legend, area);
}
@@ -266,7 +261,6 @@ 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),
+9 -125
View File
@@ -1,19 +1,16 @@
use std::collections::HashMap;
use super::frame::{Bx, CatAxis, ValAxis, frame, on, value_range};
use super::legend::{cat_label, pareto_line_color, point_color};
use super::lines::decimate;
use super::legend::{cat_label, point_color};
use super::{
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,
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,
};
// ---------------------------------------------------------------- histogram
/// 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())?;
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 };
let n = vals.len();
let span = hi - lo;
let mut bins = ((n as f64).sqrt().ceil() as usize).clamp(1, 100);
@@ -25,12 +22,13 @@ fn histogram_bins(vals: &[f64], f: &Fmt) -> Option<(Vec<String>, Vec<usize>)> {
// 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;
@@ -39,15 +37,6 @@ fn histogram_bins(vals: &[f64], f: &Fmt) -> Option<(Vec<String>, Vec<usize>)> {
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");
@@ -66,111 +55,6 @@ 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) {
-28
View File
@@ -31,32 +31,8 @@ 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![];
}
@@ -68,10 +44,6 @@ pub fn legend_entries_with(chart: &Chart, data: &ChartData, labels: &ChartLabels
(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![];
+1 -196
View File
@@ -3,13 +3,12 @@ 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; 29] = [
const ALL_KINDS: [ChartKind; 28] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -31,7 +30,6 @@ const ALL_KINDS: [ChartKind; 29] = [
ChartKind::Bubble,
ChartKind::Radar,
ChartKind::Histogram,
ChartKind::Pareto,
ChartKind::Waterfall,
ChartKind::Funnel,
ChartKind::Treemap,
@@ -156,198 +154,6 @@ 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);
@@ -666,7 +472,6 @@ 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());
-19
View File
@@ -2,32 +2,13 @@
//!
//! 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)]
+2 -2
View File
@@ -12,8 +12,8 @@ pub mod region;
pub mod value;
pub use addr::{
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,
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,
};
pub use date::DateSystem;
pub use region::Region;
+2 -3
View File
@@ -522,9 +522,8 @@ 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: 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;
/// Longest text a cell can hold, in UTF-16 code units.
pub const MAX_TEXT_CHARS: usize = 32_767;
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
pub fn cap_text(mut s: String) -> String {
-14
View File
@@ -326,20 +326,6 @@ 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
});
+6 -6
View File
@@ -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;
mod date_time;
// date_time
// filter
// financial
mod information;
mod logical;
mod math_trig;
// math_trig
mod model_info;
// other
// parent_child
// statistical
// table_manipulation
// text
mod time_intelligence;
// 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 },
Family { name: "date_time", scalar: date_time::call, table: date_time::call_table },
// date_time
// filter
// financial
Family { name: "information", scalar: information::call, table: information::call_table },
Family { name: "logical", scalar: logical::call, table: logical::call_table },
Family { name: "math_trig", scalar: math_trig::call, table: math_trig::call_table },
// math_trig
Family { name: "model_info", scalar: model_info::call, table: model_info::call_table },
// other
// parent_child
// statistical
// table_manipulation
// text
Family { name: "time_intelligence", scalar: time_intelligence::call, table: time_intelligence::call_table },
// time_intelligence
// visual
];
-613
View File
@@ -1,613 +0,0 @@
//! 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))
}
-331
View File
@@ -1,331 +0,0 @@
//! 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")?))
}
}
}
-79
View File
@@ -1,79 +0,0 @@
//! 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))
}
@@ -1,804 +0,0 @@
//! 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))
}
@@ -1,450 +0,0 @@
//! 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);
}
}
-44
View File
@@ -242,55 +242,11 @@ 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();
-565
View File
@@ -1,565 +0,0 @@
//! 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");
}
-196
View File
@@ -1,196 +0,0 @@
//! 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);
}
-632
View File
@@ -1,632 +0,0 @@
//! 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());
}
-564
View File
@@ -1,564 +0,0 @@
//! 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}");
}
-2
View File
@@ -210,7 +210,6 @@ fn undo(s: &mut Session, p: &Json) -> Result<Json> {
crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
super::extra::keep_page_breaks(d, &now);
d.calc.rebuild(&d.wb);
d.revision += 1;
Ok(json!({"undone": label}))
@@ -233,7 +232,6 @@ fn redo(s: &mut Session, p: &Json) -> Result<Json> {
crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection);
}
super::extra::keep_watch_list(&now, &mut d.wb);
super::extra::keep_page_breaks(d, &now);
d.calc.rebuild(&d.wb);
d.revision += 1;
Ok(json!({"redone": label}))
+1 -1
View File
@@ -28,7 +28,7 @@ use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline}
pub(crate) use scripts::has_scripts;
use scripts::{all_scripts, delete_script, new_script, record, run_script, stop_action, trust_scripts};
use window::{arrange_all, custom_views, hide_window, new_window, ruler, set_view, split, switch_windows, unhide_window, watch_window};
pub(crate) use window::{keep_page_breaks, keep_view_modes, keep_watch_list, window_param};
pub(crate) use window::{keep_view_modes, keep_watch_list, window_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
+2 -12
View File
@@ -72,19 +72,9 @@ pub(super) fn table_resize(s: &mut Session, p: &Json) -> Result<Json> {
} else {
None
};
// Query field identity follows the surviving physical column, even if its header was renamed.
let query_field_id = c.checked_sub(old.start.col).and_then(|i| old_cols.get(i as usize)).and_then(|x| x.query_field_id);
cols.push(match existing {
Some(x) => TableColumn { name: name.clone(), query_field_id, ..x.clone() },
None => TableColumn {
name: name.clone(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id,
xml: None,
},
Some(x) => TableColumn { name: name.clone(), ..x.clone() },
None => TableColumn { name: name.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None },
});
}
let sheet = cx.sheet_mut(si)?;
+1 -34
View File
@@ -4,8 +4,7 @@ use super::{
};
/// Switches a sheet's view. Like zoom, the view is saved with the file but is not an edit: it
/// neither records an undo step nor marks a clean workbook as changed. Page Break Preview also
/// turns on the sheet's page breaks, which Normal view then keeps showing (as in Excel).
/// neither records an undo step nor marks a clean workbook as changed.
pub(super) fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result<Json> {
let si = target_sheet(s, p)?;
let d = s.doc_mut()?;
@@ -13,9 +12,6 @@ pub(super) fn set_view(s: &mut Session, p: &Json, mode: SheetViewMode) -> Result
let wb = std::sync::Arc::make_mut(&mut d.wb);
if let Some(sh) = wb.sheet_mut(si) {
sh.view = mode;
if mode == SheetViewMode::PageBreakPreview {
sh.show_page_breaks = true;
}
}
if !dirty {
d.saved = d.wb.clone();
@@ -42,35 +38,6 @@ pub(crate) fn keep_watch_list(from: &Workbook, to: &mut std::sync::Arc<Workbook>
wb.names.extend(keep);
}
/// Show page breaks is a view setting: keep it on each surviving sheet across undo and redo.
/// Sheet identities persist through renames and moves; a restored sheet with no current identity
/// keeps its own snapshot value. A kept setting does not make a saved workbook dirty.
pub(crate) fn keep_page_breaks(d: &mut crate::DocState, from: &Workbook) {
let changed: Vec<_> =
d.wb.sheets
.iter()
.enumerate()
.filter_map(|(i, sh)| {
let on = from.sheets.iter().find(|f| f.uid.get() == sh.uid.get()).map_or(sh.show_page_breaks, |f| f.show_page_breaks);
(sh.show_page_breaks != on).then_some((i, on))
})
.collect();
if changed.is_empty() {
return;
}
let dirty = d.is_dirty();
let wb = std::sync::Arc::make_mut(&mut d.wb);
// Only the sheets that differ are copied (`sheet_mut` unshares the sheet).
for (i, on) in changed {
if let Some(sh) = wb.sheet_mut(i) {
sh.show_page_breaks = on;
}
}
if !dirty {
d.saved = d.wb.clone();
}
}
/// Normal, Page Layout and Page Break Preview belong to the window, not to the edits: Excel doesn't
/// undo a switch between them, and `set_view` is no undo step. So undo and redo keep each sheet's
/// current view when they swap in another snapshot of the workbook, and a view kept this way
+1 -10
View File
@@ -413,15 +413,7 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
totals_row: false,
columns: headers
.iter()
.map(|h| TableColumn {
name: h.clone(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
})
.map(|h| TableColumn { name: h.clone(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
.collect(),
style: "TableStyleMedium2".into(),
banded_rows: true,
@@ -432,7 +424,6 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
let q = gridcraft_formula::quote_sheet(&sheet_name);
let col_ref = |c: u32| format!("{q}!${0}$2:${0}${end_row}", col_letters(c));
+1 -1
View File
@@ -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|pareto|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|waterfall|funnel|treemap|sunburst|boxWhisker|stock, subtype?: clustered|stacked|stacked100|markers|stacked100Markers, title?, at?: \"H2\", width?, height?}",
has_doc,
insert_chart
),
+1 -6
View File
@@ -59,7 +59,6 @@ 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,
@@ -286,11 +285,7 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
},
title,
series,
legend: match kind {
ChartKind::Pie | ChartKind::Doughnut => LegendPos::Right,
ChartKind::Pareto => LegendPos::None,
_ => LegendPos::Bottom,
},
legend: if matches!(kind, ChartKind::Pie | ChartKind::Doughnut) { LegendPos::Right } else { LegendPos::Bottom },
data_labels: false,
data_table: None,
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
+1 -10
View File
@@ -112,15 +112,7 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
totals_row: false,
columns: names
.into_iter()
.map(|n| TableColumn {
name: n,
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
})
.map(|n| TableColumn { name: n, totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
.collect(),
style,
banded_rows: true,
@@ -131,7 +123,6 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
});
cx.structural = true;
Ok(json!({"table": name, "range": r.a1()}))
+2 -2
View File
@@ -56,7 +56,7 @@ const MAX_CHART_PRIMS: usize = 4_000_000;
#[cfg(test)]
use layout::bands;
pub(crate) use layout::split_bands;
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, page_break_bands, paper_size, print_range};
pub use layout::{PrintOptions, SheetLayout, layout_sheet, layouts, paper_size, print_range};
use layout::{seg_size, segments};
use objects::{PicCache, draw_objects};
#[cfg(test)]
@@ -96,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Page Setup…",
["Page Layout", "Page Setup"],
None,
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A0|A1|A2|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown, excluded?: bool (left out when the whole workbook prints, unless every visible sheet is)} → the sheet's print settings",
"{sheet?, orientation?: portrait|landscape, paper?: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes), margins?: {left,right,top,bottom,header,footer} (inches; also accepted as top-level keys), scale?: 10..400, fitWidth?, fitHeight? (pages; 0 = automatic), fitToPage?: bool, centerH?, centerV?, gridlines?, headings?, header?: \"&L&A&RPage &P of &N\", footer?, printArea?: \"A1:F50\" (\"\" clears), titleRows?: \"1:2\", titleCols?: \"A:A\", rowBreaks?: [46, 91], colBreaks?: [\"K\"], pageOrder?: downThenOver|overThenDown, excluded?: bool (left out when the whole workbook prints, unless every visible sheet is)} → the sheet's print settings",
has_doc,
page_setup
),
+1 -19
View File
@@ -353,7 +353,7 @@ pub(crate) fn page_sequence(rows: usize, cols: usize, order: PageOrder, cap: usi
}
/// Inclusive-start/end index spans of the pages along one axis.
pub type Bands = Vec<(u32, u32)>;
pub(crate) type Bands = Vec<(u32, u32)>;
/// Splits a layout's area into row and column bands that fit its pages (at most `cap` of each),
/// honouring manual breaks (when `lay.manual_breaks`), print headings and repeated titles. The
@@ -386,24 +386,6 @@ pub(crate) fn split_bands(sh: &Sheet, lay: &SheetLayout, cap: usize) -> (Bands,
(rows, cols)
}
/// Page bands for the grid's editing overlay, extending only the last printed bands to their
/// actual printable capacity. The original layout, print area, scale and page sequence stay intact.
pub fn page_break_bands(sh: &Sheet, lay: &SheetLayout) -> (Bands, Bands) {
let (Some(row), Some(col)) = (lay.row_bands.last(), lay.col_bands.last()) else { return (Vec::new(), Vec::new()) };
let mut tail = lay.clone();
tail.area = RangeRef::new(CellRef::new(row.0, col.0), CellRef::new(MAX_ROWS - 1, MAX_COLS - 1));
let (rows, cols) = split_bands(sh, &tail, 1);
let mut out_rows = lay.row_bands.clone();
let mut out_cols = lay.col_bands.clone();
if let (Some(last), Some(extended)) = (out_rows.last_mut(), rows.first()) {
*last = *extended;
}
if let (Some(last), Some(extended)) = (out_cols.last_mut(), cols.first()) {
*last = *extended;
}
(out_rows, out_cols)
}
/// Lays out every sheet a print command covers.
pub fn layouts(wb: &Workbook, opts: &PrintOptions) -> Vec<SheetLayout> {
let mut out = Vec::new();
-26
View File
@@ -22,29 +22,6 @@ fn arabic_face_available() -> bool {
!doc.missing_arabic_font()
}
#[test]
fn editing_page_boundaries_follow_paper_and_orientation_without_changing_print_range() {
let mut wb = Workbook::new();
wb.sheet_mut(0).unwrap().print.paper = "A4".into();
let overlay = |wb: &Workbook| {
let layout = layout_sheet(wb, 0, &PrintOptions::default(), None).unwrap();
let original = (layout.area, layout.row_bands.clone(), layout.col_bands.clone(), layout.pages.clone());
let (rows, cols) = page_break_bands(wb.sheet(0).unwrap(), &layout);
assert_eq!((layout.area, layout.row_bands.clone(), layout.col_bands.clone(), layout.pages.clone()), original);
assert_eq!(layout.row_bands.len(), 1);
assert_eq!(layout.col_bands.len(), 1);
(rows[0].1, cols[0].1)
};
let portrait = overlay(&wb);
assert!(portrait.0 > 0 && portrait.1 > 0, "an empty one-page sheet still shows its capacity");
wb.sheet_mut(0).unwrap().print.orientation = Orientation::Landscape;
let landscape = overlay(&wb);
assert!(landscape.1 > portrait.1 && landscape.0 < portrait.0);
wb.sheet_mut(0).unwrap().print.paper = "A3".into();
let larger = overlay(&wb);
assert!(larger.0 > landscape.0 && larger.1 > landscape.1);
}
#[test]
fn right_to_left_sheets_mirror_link_rectangles_and_targets() {
fn numbers_after(pdf: &[u8], key: &str, n: usize) -> Vec<f32> {
@@ -965,9 +942,6 @@ fn page_setup_edits_settings() {
fn japanese_paper_sizes_are_jis() {
for (name, w, h) in [
("A4", 595.28, 841.89), // unchanged
("A2", 1190.55, 1683.78),
("a1", 1683.78, 2383.94),
("A0", 2383.94, 3370.39),
("B4", 728.50, 1031.81),
("B5", 515.91, 728.50),
("B6", 362.83, 515.91),
+6 -70
View File
@@ -727,80 +727,17 @@ fn check_lines_protection(s: &Session, p: &Json, axis: Axis, at: u32, count: u32
return Ok(());
}
let end = at.saturating_add(count - 1).min(if axis == Axis::Rows { MAX_ROWS - 1 } else { MAX_COLS - 1 });
let lines = LockedLines::of(sh, axis, &locked);
if !(at..=end).all(|i| lines.unlocked(sh, i, &locked)) {
let infos = if axis == Axis::Rows { &sh.rows } else { &sh.cols };
if (at..=end).any(|i| locked(infos.get(&i).and_then(|x| x.style).unwrap_or_default())) {
return Err(refuse());
}
let block = if axis == Axis::Rows { RangeRef::rows(at, end) } else { RangeRef::cols(at, end) };
if sh.cells.iter_range(block).any(|(_, cell)| locked(cell.style)) {
return Err(refuse());
}
Ok(())
}
/// Whether every cell of a row or column is unlocked, which Excel requires before it deletes the
/// line on a protected sheet ("You are trying to delete a row that contains a locked cell"),
/// however the Delete Rows or Delete Columns permission is set.
///
/// A cell the sheet does not store is judged by the style `Sheet::style_id` gives it: its row's
/// format, then its column's, then the default: the workbook's Normal style, locked unless the
/// file unlocked it (see `unlocked`). Reading a line with no format of
/// its own as the default refused every delete, even over a row the user had unlocked through
/// its columns; reading it as unlocked passed a blank row whose cells are all locked by default.
/// The cross lines' formats are summarised once here, since a delete can span a million rows.
struct LockedLines {
axis: Axis,
/// Cross lines (columns for a row, rows for a column) whose own format is locked.
locked_cross: Vec<u32>,
/// How many cross lines have no format of their own, and so no say over a cell they cross.
plain_count: u32,
}
impl LockedLines {
fn of(sh: &Sheet, axis: Axis, locked: &impl Fn(gridcraft_model::StyleId) -> bool) -> Self {
let (cross, cross_len) = if axis == Axis::Rows { (&sh.cols, MAX_COLS) } else { (&sh.rows, MAX_ROWS) };
let styled: Vec<_> = cross.iter().filter_map(|(k, x)| x.style.map(|st| (*k, st))).collect();
let locked_cross = styled.iter().filter(|(_, st)| locked(*st)).map(|(k, _)| *k).collect();
Self { axis, locked_cross, plain_count: cross_len - styled.len() as u32 }
}
fn unlocked(&self, sh: &Sheet, i: u32, locked: &impl Fn(gridcraft_model::StyleId) -> bool) -> bool {
let rows = self.axis == Axis::Rows;
let (line, cross_len) = if rows { (RangeRef::rows(i, i), MAX_COLS) } else { (RangeRef::cols(i, i), MAX_ROWS) };
let mut stored = std::collections::HashSet::new();
for (at, cell) in sh.cells.iter_range(line) {
if locked(cell.style) {
return false;
}
stored.insert(if rows { at.col } else { at.row });
}
if stored.len() as u32 == cross_len {
return true;
}
let (own_lines, cross) = if rows { (&sh.rows, &sh.cols) } else { (&sh.cols, &sh.rows) };
let own = own_lines.get(&i).and_then(|x| x.style);
// A row's own format is the first one its empty cells take, so it decides alone.
if rows && let Some(st) = own {
return !locked(st);
}
// Otherwise a cross line's locked format reaches every cell of this line it crosses
// (for a column, a row's format comes before the column's own).
if self.locked_cross.iter().any(|k| !stored.contains(k)) {
return false;
}
// The cells left are those under a cross line with no format. Deleting a column, they take
// the column's own format, which may unlock them all. Deleting a row, neither line has a
// format, so they take the default; when it is locked, each has to be a stored cell, and
// the stored ones were all checked above.
if !rows && own.is_some_and(|st| !locked(st)) {
return true;
}
// Neither line has a format, so the cells take the workbook's Normal style, which a file
// may have unlocked: then they all are.
if own.is_none() && !locked(gridcraft_model::StyleId::DEFAULT) {
return true;
}
let plain = stored.iter().filter(|k| !cross.get(k).is_some_and(|x| x.style.is_some())).count();
plain as u32 == self.plain_count
}
}
/// Where a range of the edited sheet goes after a structural edit (`None` = deleted).
pub(crate) fn map_range(r: RangeRef, e: &Edit) -> Option<RangeRef> {
let expr = gridcraft_formula::Expr::Ref(gridcraft_formula::Reference {
@@ -958,7 +895,6 @@ fn shift_table_columns(t: &mut gridcraft_model::Table, at: u32, count: u32, inse
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
};
t.columns.insert((idx + k).min(t.columns.len()), col);
+1 -30
View File
@@ -38,15 +38,6 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("view.gridlines", "Gridlines", ["View", "Show"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "gridlines")),
cmd!("view.headings", "Headings", ["View", "Show"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "headings")),
cmd!("view.showZeros", "Show Zeros", [], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "zeros")),
cmd!(
noundo "view.showPageBreaks",
"Show Page Breaks",
[],
None,
"{sheet?, on?} → {on}: dashed page boundaries in Normal view (a display option, not saved with the file)",
has_doc,
show_page_breaks
),
cmd!("view.showOutlineSymbols", "Show Outline Symbols", [], Some("Ctrl+8"), "{on?}", has_doc, |s, p| sheet_flag(s, p, "outlineSymbols")),
cmd!("view.showObjects", "Show Objects", [], Some("Ctrl+6"), "{on?}", has_doc, show_objects),
cmd!(
@@ -93,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Size",
["Page Layout", "Page Setup"],
None,
"{paper: Letter|Legal|A0|A1|A2|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
"{paper: Letter|Legal|A4|A3|A5|A6|Tabloid|Executive|Ledger|B4|B5|B6|B4 (ISO)|B5 (ISO)|B6 (ISO)|Japanese Postcard|Japanese Double Postcard|Japanese Envelope #3|Japanese Envelope #4|Japanese Envelope Kaku #2|Japanese Envelope Kaku #3|Statement|Envelope #10|Envelope DL (B4/B5/B6 are the JIS sizes)}",
has_doc,
paper
),
@@ -234,26 +225,6 @@ fn workbook_view_flag(s: &mut Session, p: &Json, which: &str) -> Result<Json> {
})
}
/// Excel's Show page breaks: a display option of the sheet, so it neither records an undo step
/// nor marks a clean workbook as changed (like `set_view`).
fn show_page_breaks(s: &mut Session, p: &Json) -> Result<Json> {
let si = target_sheet(s, p)?;
let d = s.doc_mut()?;
let dirty = d.is_dirty();
let current = d.wb.sheet(si).is_some_and(|sh| sh.show_page_breaks);
let on = bool_param(p, "on").unwrap_or(!current);
if on != current {
let wb = std::sync::Arc::make_mut(&mut d.wb);
if let Some(sh) = wb.sheet_mut(si) {
sh.show_page_breaks = on;
}
if !dirty {
d.saved = d.wb.clone();
}
}
Ok(json!({"on": on}))
}
/// Ctrl+6: hides every object, or shows them again. Placeholders (from a file) count as shown.
fn show_objects(s: &mut Session, p: &Json) -> Result<Json> {
use gridcraft_model::ShowObjects;
-1
View File
@@ -904,7 +904,6 @@ mod tests {
filter: Vec::new(),
table_type: None,
connection_id: None,
query_table: None,
});
let inputs = vec![("Input".to_string(), place("B2:D2"), true), ("Plain".to_string(), place("B2:D2"), false)];
let env = Env { wb: &wb, active_sheet: 0, inputs: &inputs, output: None, item: None };
-1
View File
@@ -695,7 +695,6 @@ fn grow_right(
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
});
cx.rebuild_deps = true;
-203
View File
@@ -3947,84 +3947,6 @@ fn show_outline_symbols_toggles() {
assert!(!on(&s));
}
/// Show page breaks (Excel: Options › Advanced, per worksheet): off on a new sheet, turned on by
/// Page Break Preview and kept in Normal view, switched without making the workbook dirty.
#[test]
fn page_break_preview_turns_on_show_page_breaks_for_its_sheet() {
let mut s = s();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
let wb = s.doc().unwrap().wb.clone();
s.doc_mut().unwrap().saved = wb;
let on = |s: &Session, name: &str| s.active().unwrap().wb.sheets.iter().find(|x| x.name == name).unwrap().show_page_breaks;
assert!(!on(&s, "Two"));
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("view.normal", json!({})).unwrap();
assert!(on(&s, "Two"), "Normal view keeps the page breaks Page Break Preview showed");
assert!(!on(&s, "Sheet1"), "only the previewed sheet");
assert_eq!(s.execute("view.showPageBreaks", json!({})).unwrap(), json!({"on": false}));
assert!(!on(&s, "Two"));
assert_eq!(s.execute("view.showPageBreaks", json!({"on": true})).unwrap(), json!({"on": true}));
assert!(on(&s, "Two"));
assert!(!s.doc().unwrap().is_dirty(), "a display option, not an edit");
}
/// Undo and redo swap in another snapshot of the workbook; the page breaks shown stay as they are
/// (a display option isn't undone), matched by sheet name.
#[test]
fn undo_and_redo_keep_show_page_breaks() {
let mut s = s();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("view.normal", json!({})).unwrap();
let on = |s: &Session| s.active().unwrap().wb.active().unwrap().show_page_breaks;
assert!(on(&s));
s.execute("edit.undo", json!({})).unwrap();
assert!(on(&s), "undoing the typing leaves the page breaks on");
s.execute("view.showPageBreaks", json!({"on": false})).unwrap();
s.execute("edit.redo", json!({})).unwrap();
assert!(!on(&s), "redo doesn't bring back the snapshot's page breaks either");
assert!(s.active().unwrap().wb.active().unwrap().cell(CellRef::new(0, 0)).is_some(), "the redo itself happened");
}
/// Undoing a rename brings back a sheet name the current workbook doesn't have: its page breaks
/// stay as the snapshot has them, not off.
#[test]
fn undoing_a_rename_keeps_show_page_breaks() {
let mut s = s();
s.execute("view.pageBreakPreview", json!({})).unwrap();
s.execute("view.normal", json!({})).unwrap();
s.execute("sheet.rename", json!({"name": "Renamed"})).unwrap();
let on = |s: &Session| s.active().unwrap().wb.active().unwrap().show_page_breaks;
assert!(on(&s));
s.execute("view.showPageBreaks", json!({"on": false})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_ne!(s.active().unwrap().wb.active().unwrap().name, "Renamed", "the rename was undone");
assert!(!on(&s), "the current setting survives the undone rename");
s.execute("edit.redo", json!({})).unwrap();
assert!(!on(&s), "the current setting survives the redone rename");
}
/// A grouped rename can reuse another sheet's name. View state follows identity, not that name.
#[test]
fn grouped_renames_keep_page_breaks_on_the_same_sheets() {
let mut s = s();
s.execute("home.insertSheet", json!({"name": "Two"})).unwrap();
s.grouped("Rename sheets", |s| {
s.execute("sheet.rename", json!({"sheet": "Sheet1", "name": "Temp"}))?;
s.execute("sheet.rename", json!({"sheet": "Two", "name": "Sheet1"}))?;
Ok(())
})
.unwrap();
s.execute("view.showPageBreaks", json!({"sheet": "Temp", "on": true})).unwrap();
let on = |s: &Session, name: &str| s.active().unwrap().wb.sheets.iter().find(|sh| sh.name == name).unwrap().show_page_breaks;
s.execute("edit.undo", json!({})).unwrap();
assert!(on(&s, "Sheet1"));
assert!(!on(&s, "Two"));
s.execute("edit.redo", json!({})).unwrap();
assert!(on(&s, "Temp"));
assert!(!on(&s, "Sheet1"));
}
fn reopen(s: &mut Session) {
let r = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap();
let b64 = r["base64"].as_str().unwrap().to_string();
@@ -4120,7 +4042,6 @@ 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),
@@ -4152,16 +4073,6 @@ 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();
@@ -7611,120 +7522,6 @@ fn unique_nonce() -> u64 {
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
/// Protect Sheet's Delete Rows and Delete Columns delete a line only when every cell in it is
/// unlocked, as Excel does ("You are trying to delete a row that contains a locked cell"). The
/// line-level check read a line without a format of its own as carrying the default style, which
/// is locked, so every delete was refused however the permission was set; a cell the sheet does
/// not store is judged by the format it shows, its row's, then its column's, then the default.
#[test]
fn a_protected_sheet_deletes_blank_lines_when_the_normal_style_is_unlocked() {
// A file whose Normal style is unlocked leaves every unformatted cell unlocked, stored or not.
let mut sess = s();
sess.execute("review.protectSheet", json!({})).unwrap();
{
let d = sess.doc_mut().unwrap();
let mut wb = (*d.wb).clone();
let mut normal = wb.styles.get(gridcraft_model::StyleId::DEFAULT).clone();
normal.protection.locked = false;
wb.styles = gridcraft_model::StyleTable::with_default(normal);
// The sheet must be protected, or the deletes below would pass without checking anything.
let p = wb.sheet_mut(0).and_then(|sh| sh.protection.as_mut()).expect("review.protectSheet protected sheet 0");
p.delete_rows = true;
p.delete_columns = true;
d.wb = std::sync::Arc::new(wb);
}
sess.execute("selection.set", json!({"range": "A7:A7"})).unwrap();
assert!(sess.execute("home.deleteRows", json!({})).is_ok(), "a blank row of unlocked default cells");
sess.execute("selection.set", json!({"range": "F1:F1"})).unwrap();
assert!(sess.execute("home.deleteColumns", json!({})).is_ok(), "a blank column of unlocked default cells");
}
#[test]
fn a_protected_sheet_deletes_lines_when_it_says_so() {
fn grant(sess: &mut Session) {
let d = sess.doc_mut().unwrap();
let mut wb = (*d.wb).clone();
if let Some(p) = wb.sheet_mut(0).and_then(|sh| sh.protection.as_mut()) {
p.delete_rows = true;
p.delete_columns = true;
}
d.wb = std::sync::Arc::new(wb);
}
// Values in A1:A3, the given ranges unlocked (or locked again) in order, then protected.
let book = |locks: &[(&str, bool)], granted: bool| {
let mut sess = s();
for (c, v) in [("A1", "1"), ("A2", "2"), ("A3", "3")] {
sess.execute("cell.set", json!({"cell": c, "input": v})).unwrap();
}
for (range, on) in locks {
sess.execute("home.lockCell", json!({"range": range, "on": on})).unwrap();
}
sess.execute("review.protectSheet", json!({})).unwrap();
if granted {
grant(&mut sess);
}
sess
};
let delete = |sess: &mut Session, what: &str, at: &str| {
sess.execute("selection.set", json!({"range": format!("{at}:{at}")})).unwrap();
sess.execute(what, json!({})).is_ok()
};
let (rows, cols) = ("home.deleteRows", "home.deleteColumns");
const SHEET: &str = "A1:XFD1048576";
// Granted, over whole rows the user unlocked: the row goes, and the rows below move up.
let mut sess = book(&[("A1:XFD10", false)], true);
assert!(delete(&mut sess, rows, "A1"), "an unlocked row is deleted");
assert_eq!((v(&sess, "A1"), v(&sess, "A2")), (Value::Number(2.0), Value::Number(3.0)));
// Its columns still have locked cells below row 10, so a column is not deleted.
assert!(!delete(&mut sess, cols, "A1"), "a column with locked cells stays");
// Granted, over a whole column the user unlocked: the column goes.
let mut sess = book(&[("A1:A1048576", false)], true);
assert!(delete(&mut sess, cols, "A1"), "an unlocked column is deleted");
assert_eq!(v(&sess, "A1"), Value::Empty);
// Granted, with the whole sheet unlocked: blank lines go too, judged by their columns' format.
let mut sess = book(&[(SHEET, false)], true);
assert!(delete(&mut sess, rows, "A7"), "a blank row under unlocked columns");
assert!(delete(&mut sess, cols, "F1"), "a blank unlocked column");
// Not granted: refused, and the rows stay.
let mut sess = book(&[(SHEET, false)], false);
assert!(!delete(&mut sess, rows, "A1"), "Delete rows is off");
assert!(!delete(&mut sess, cols, "A1"), "Delete columns is off");
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
// Granted, but only a block of cells is unlocked: the rest of each line is locked by default,
// so neither its rows nor its columns are deleted.
let mut sess = book(&[("A1:D10", false)], true);
assert!(!delete(&mut sess, rows, "A1"), "E1 onwards are locked");
assert!(!delete(&mut sess, cols, "A1"), "A11 onwards are locked");
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
// Granted, nothing unlocked: a blank line is locked by the default like any other, and a line
// with a locked value in it is refused by that cell.
let mut sess = book(&[], true);
assert!(!delete(&mut sess, rows, "A7"), "a blank row of default cells is locked");
assert!(!delete(&mut sess, cols, "F1"), "a blank column of default cells is locked");
assert!(!delete(&mut sess, rows, "A1"), "locked cells are not deleted");
assert_eq!(v(&sess, "A1"), Value::Number(1.0));
// Granted, the sheet unlocked but row 5 locked again by a format of its own: row 5 is refused,
// and so is every column, since row 5's format comes before a column's in each cell it crosses.
// The format has to go on before the sheet is protected, since changing a format on a
// protected sheet is itself refused.
let mut sess = book(&[(SHEET, false), ("A5:XFD5", true)], true);
assert!(!delete(&mut sess, rows, "A5"), "a locked row format refuses");
assert!(!delete(&mut sess, cols, "B1"), "B5 is locked by its row");
assert!(delete(&mut sess, rows, "A6"), "the rows beside it are not");
// An unprotected sheet is untouched by any of this.
let mut sess = s();
sess.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
sess.execute("home.deleteRows", json!({})).unwrap();
}
/// Normal, Page Layout and Page Break Preview are not undo steps (as in Excel), so undoing or
/// redoing an edit keeps each sheet in the view it is in now, instead of putting back the view
/// of the snapshot it swaps in. Found through the command-sequence fuzz (seed 177).
-321
View File
@@ -317,327 +317,6 @@ 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.
@@ -530,7 +530,7 @@ fn watch_list(wb: &Workbook) -> Option<&str> {
}
/// The workbook with view state (active sheet, scroll, active cell, zoom, Normal / Page Layout /
/// Page Break Preview, Show page breaks) and the Watch Window list reset: undo restores view state as it was, but
/// Page Break Preview) and the Watch Window list reset: undo restores view state as it was, but
/// switching sheets, zooming or switching views isn't an undoable edit.
fn canonical(wb: &Workbook) -> Workbook {
let mut wb = wb.clone();
@@ -542,8 +542,6 @@ fn canonical(wb: &Workbook) -> Workbook {
sh.view_top_left = CellRef::default();
sh.zoom = 100;
sh.view = SheetViewMode::Normal;
// Page Break Preview turns Show page breaks on, a display option that isn't an edit either.
sh.show_page_breaks = false;
}
wb
}
+2 -11
View File
@@ -600,15 +600,8 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
{
let wb = std::sync::Arc::make_mut(&mut st.active_mut().unwrap().wb);
let sh = wb.sheet_mut(0).unwrap();
let col = |name: &str| TableColumn {
name: name.into(),
totals: TotalsFn::None,
totals_label: None,
formula: None,
unique_name: None,
query_field_id: None,
xml: None,
};
let col =
|name: &str| TableColumn { name: name.into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None };
sh.tables.push(Table {
id: 1,
name: "LeftTable".into(),
@@ -625,7 +618,6 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
filter: vec![(0, FilterCriterion::Values { values: vec![" ".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
query_table: None,
});
sh.tables.push(Table {
id: 2,
@@ -643,7 +635,6 @@ fn migration_preserves_manual_hidden_rows_and_sibling_table_filters_2943() {
filter: vec![(0, FilterCriterion::Values { values: vec!["East".into()], blanks: false, identities: vec![] })],
table_type: None,
connection_id: None,
query_table: None,
});
sh.rows.entry(1).or_default().hidden = true;
sh.rows.entry(2).or_default().hidden = true;
@@ -55,31 +55,6 @@ fn resize_next_to_another_table_still_works() {
assert_eq!(ranges(&s), ["A1:C3", "D1:E2"]);
}
#[test]
fn resize_keeps_a_renamed_column_query_field() {
let mut s = table();
let d = s.doc_mut().unwrap();
let si = d.wb.active_sheet();
std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns[1].query_field_id = Some(7);
s.execute("range.setValues", json!({"range":"B1", "values":[["Amount"]]})).unwrap();
s.execute("table.resize", json!({"table":"T", "range":"A1:B3"})).unwrap();
let col = &s.doc().unwrap().wb.active().unwrap().tables[0].columns[1];
assert_eq!((col.name.as_str(), col.query_field_id), ("Amount", Some(7)));
}
#[test]
fn resize_preserves_query_fields_only_for_surviving_addresses() {
let mut s = table();
let d = s.doc_mut().unwrap();
let si = d.wb.active_sheet();
let columns = &mut std::sync::Arc::make_mut(&mut d.wb).sheet_mut(si).unwrap().tables[0].columns;
columns[0].query_field_id = Some(3);
columns[1].query_field_id = Some(7);
s.execute("table.resize", json!({"table":"T", "range":"B1:C3"})).unwrap();
let cols = &s.doc().unwrap().wb.active().unwrap().tables[0].columns;
assert_eq!(cols.iter().map(|c| c.query_field_id).collect::<Vec<_>>(), [Some(7), None]);
}
fn sheet(s: &Session) -> &gridcraft_engine::model::Sheet {
s.doc().unwrap().wb.active().unwrap()
}
+2 -72
View File
@@ -23,19 +23,6 @@ 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
@@ -246,12 +233,6 @@ 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));
@@ -311,20 +292,13 @@ 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 = xneedle(args, 0)?;
let x = needle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -370,7 +344,7 @@ fn xlookup(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
}
fn xmatch(args: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
let x = xneedle(args, 0)?;
let x = needle(args, 0)?;
let lv = &arg(args, 1)?.value;
if let Value::Error(e) = lv {
return Err(*e);
@@ -593,7 +567,6 @@ pub(crate) fn specs() -> Vec<FnSpec> {
mod tests {
use gridcraft_core::{CellError, Value};
use crate::Arg;
use crate::util::testutil::*;
fn table() -> Value {
@@ -786,49 +759,6 @@ 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() {
+3 -3
View File
@@ -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, 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,
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,
};
#[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.",
hypgeomdist_legacy
hypgeom_dist
),
f!(
"NEGBINOM.DIST",
+2 -22
View File
@@ -804,27 +804,15 @@ 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() })
}
fn hypgeom_common(a: &[Arg], strict: bool) -> R<Value> {
pub(super) fn hypgeom_dist(a: &[Arg], _: C) -> 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 {
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) {
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));
@@ -841,14 +829,6 @@ fn hypgeom_common(a: &[Arg], strict: bool) -> 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();
-19
View File
@@ -821,25 +821,6 @@ 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);
-9
View File
@@ -60,10 +60,6 @@ pub struct TableColumn {
/// `uniqueName`: the name XML maps know the column by.
#[serde(default)]
pub unique_name: Option<String>,
/// `queryTableFieldId`: the field of the table's query table this column shows. It moves with
/// the column; inserted columns have none.
#[serde(default)]
pub query_field_id: Option<u32>,
/// Binding to an element of an XML map. It moves with the column and goes when the column is
/// deleted; inserted columns are unmapped.
#[serde(default)]
@@ -106,10 +102,6 @@ pub struct Table {
/// The connection (`xl/connections.xml`) an XML table is bound through.
#[serde(default)]
pub connection_id: Option<u32>,
/// The XML of the table's query table part (`xl/queryTables/…`), kept as read so the table
/// stays attached to its data connection. Never refreshed.
#[serde(default)]
pub query_table: Option<String>,
}
impl Table {
@@ -521,7 +513,6 @@ pub enum ChartKind {
Bubble,
Radar,
Histogram,
Pareto,
Waterfall,
Funnel,
Treemap,
+1 -4
View File
@@ -6,14 +6,11 @@
/// saved under. `B4`/`B5`/`B6` are the **JIS** sizes Japanese Excel uses (257×364, 182×257 and
/// 128×182 mm); the ISO B series is `B4 (ISO)`/`B5 (ISO)`/`B6 (ISO)`. The Japanese postcards and
/// envelopes are the JIS ones too.
pub const PAPERS: [(&str, f32, f32); 27] = [
pub const PAPERS: [(&str, f32, f32); 24] = [
("Letter", 612.0, 792.0),
("Legal", 612.0, 1008.0),
("A4", 595.28, 841.89),
("A3", 841.89, 1190.55),
("A2", 1190.55, 1683.78),
("A1", 1683.78, 2383.94),
("A0", 2383.94, 3370.39),
("A5", 419.53, 595.28),
("A6", 297.64, 419.53),
("Tabloid", 792.0, 1224.0),
-5
View File
@@ -131,10 +131,6 @@ pub struct Sheet {
#[serde(default = "yes")]
pub summary_right: bool,
pub right_to_left: bool,
/// Excel's Show page breaks (Options › Advanced, "Display options for this worksheet"): dashed
/// page boundaries in Normal view. Page Break Preview turns it on; not saved with the file.
#[serde(skip)]
pub show_page_breaks: bool,
pub zoom: u16,
pub cond_formats: Vec<CondFormat>,
pub validations: Vec<Validation>,
@@ -215,7 +211,6 @@ impl Sheet {
show_formulas: false,
show_zeros: true,
right_to_left: false,
show_page_breaks: false,
zoom: 100,
cond_formats: vec![],
validations: vec![],
-1
View File
@@ -16,7 +16,6 @@ craft-behavior = { workspace = true }
craft-host = { workspace = true }
craft-keymap = { workspace = true }
craft-print = { workspace = true }
craft-quit = { workspace = true }
craft-theme = { workspace = true }
craft-window = { workspace = true }
gridcraft-engine = { workspace = true }
+2 -21
View File
@@ -93,7 +93,6 @@ impl SheetApp {
#[cfg(not(target_arch = "wasm32"))]
updates_rt: Default::default(),
framework_dialogs: Default::default(),
unsaved_prompt: None,
framework_host: crate::framework::host(),
}
}
@@ -206,9 +205,6 @@ impl SheetApp {
let t0 = now_ms();
// A script may have switched windows since the last frame.
self.follow_active_window();
// The window this pass draws: a command run in it may switch to another window, which draws
// in its own pass.
let drawn = self.ui_window();
// This window's key tip request that waited for this frame (its tab or ribbon was just
// shown); any other window's request was dropped before it.
self.ui.keytip_invoke = self.ui.keytip_invoke_next.take();
@@ -271,13 +267,10 @@ impl SheetApp {
widgets::toast(self, &ctx);
// Last, so its resize cursors win over the widgets under the window edges.
ribbon::window_frame(self, &ctx);
// The update flow runs once per frame, in the root window; the framework dialogs too, unless
// the unsaved-changes question asks about a workbook in another window: they show there.
#[cfg(not(target_arch = "wasm32"))]
// The update flow and the framework dialogs run once per frame, in the root window.
if ctx.viewport_id() == egui::ViewportId::ROOT {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
}
if self.framework_dialogs_here(&ctx, drawn) {
self.run_framework_dialogs(ui);
}
self.flush_viewport_commands(&ctx);
@@ -309,18 +302,6 @@ impl SheetApp {
}
}
/// Whether a modal question is up and owns the keyboard: a GridCraft dialog or the shared
/// unsaved-changes question.
pub fn modal_open(&self) -> bool {
self.dialog.is_some() || self.unsaved_prompt.is_some()
}
/// The name of the open dialog, for automation: a GridCraft dialog's, or `saveChanges` while
/// the shared unsaved-changes question is up.
pub fn open_dialog_name(&self) -> Option<&str> {
self.dialog.as_ref().map(|d| d.name()).or_else(|| self.unsaved_prompt.as_ref().map(|_| "saveChanges"))
}
/// Current selection's top-left cell text as A1 (for the Name Box).
pub fn name_box_text(&self) -> String {
let Some(d) = self.session.active() else { return String::new() };
+1 -6
View File
@@ -298,8 +298,6 @@ 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(", "))),
@@ -307,12 +305,10 @@ 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)),
@@ -335,7 +331,7 @@ impl SheetApp {
"ui.dialog" => {
let name = p.get("name").and_then(Json::as_str).unwrap_or("");
self.open_dialog(name, p.clone());
Ok(json!({"dialog": self.open_dialog_name()}))
Ok(json!({"dialog": self.dialog.as_ref().map(|d| d.name())}))
}
"ui.selectionMode" => {
// `{"mode": "extend"}` (F8), `"add"` (Shift+F8) or `"off"`; `{}` reports the mode.
@@ -481,7 +477,6 @@ impl SheetApp {
}
// The notice AutoSave holds back with: Save asks what the notice says.
"saveLoss" => self.run_or_alert("file.save", json!({})),
"saveChanges" => self.open_unsaved_changes(&params),
// File › Options (`file.options`) and the File tab itself open the Backstage view.
"options" => self.open_backstage(backstage::Page::Options),
"backstage" => {
+1 -1
View File
@@ -4,7 +4,7 @@ impl SheetApp {
pub(super) fn ribbon_keys(&mut self, ctx: &egui::Context) {
let before = self.keytips.prefix().map(str::to_string);
let enabled = self.editor.is_none()
&& !self.modal_open()
&& self.dialog.is_none()
&& self.message.is_none()
&& self.name_box.is_none()
&& !ctx.text_edit_focused()
+7 -82
View File
@@ -1,10 +1,7 @@
use craft_quit::{CloseAnswer, CloseScope};
use craft_ui::dialog::{DialogResult, UnsavedAnswer, UnsavedChangesDialog};
use craft_ui::shell::embed::CloseDecision;
use gridcraft_engine::cmd::file::{SaveLosses, save_losses, xlsx_save_losses};
use super::{AfterSave, Json, PendingSave, SaveAnswer, SaveLossAnswer, SaveRequest, SheetApp, json};
use crate::state::UnsavedPrompt;
impl SheetApp {
/// The root window was asked to close (the close button, Alt+F4, the OS quitting the app): whether it closes
@@ -34,11 +31,12 @@ impl SheetApp {
if !self.session.documents().iter().any(|d| d.is_dirty()) {
return CloseDecision::Close;
}
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
match self.dialog.as_mut() {
// Already asking about a workbook (File › Close): answering it now goes on to quit.
self.promote_unsaved_to_quit();
} else {
self.continue_quit(ctx);
Some(d) if d.name() == "saveChanges" => {
d.values.insert("quit".into(), json!(true));
}
_ => self.continue_quit(ctx),
}
CloseDecision::Hold
}
@@ -235,86 +233,13 @@ impl SheetApp {
crate::macro_editor::request_close(self, true);
return;
}
if self.framework_dialogs.is_open::<UnsavedChangesDialog>() {
if let Some(d) = self.dialog.as_mut().filter(|d| d.name() == "saveChanges") {
// Already asking about a workbook (File › Close): answering it goes on to quit.
self.promote_unsaved_to_quit();
d.values.insert("quit".into(), json!(true));
return;
}
self.continue_quit(ctx);
}
/// Opens the shared unsaved-changes dialog on `framework_dialogs` for the active workbook.
pub(crate) fn open_unsaved_changes(&mut self, params: &Json) {
if self.dialog.as_ref().is_some_and(|d| d.name == "macroEditor") {
self.message = Some((
"Macro".into(),
"Close the macro step editor first: it keeps its window until it closes itself, so its steps and debug run are not lost.".into(),
));
return;
}
if let Some(mut old) = self.dialog.take() {
let _ = old.end_pick(self);
}
let Some(doc) = self.session.active().map(|d| d.uid) else { return };
let title = params
.get("title")
.and_then(Json::as_str)
.map(str::to_owned)
.or_else(|| self.session.active().map(|d| d.display_title()))
.unwrap_or_else(|| "this workbook".into());
let quitting = params.get("quit").and_then(Json::as_bool) == Some(true);
let scope = if quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(UnsavedPrompt { doc, window: self.ui_window(), quitting });
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
// A replaced question leaves a Cancel result; it is not the new question's answer.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
fn promote_unsaved_to_quit(&mut self) {
if let Some(prompt) = self.unsaved_prompt.as_mut()
&& !prompt.quitting
{
prompt.quitting = true;
let title =
self.session.documents().iter().find(|d| d.uid == prompt.doc).map(|d| d.display_title()).unwrap_or_else(|| "this workbook".into());
self.framework_dialogs.open(UnsavedChangesDialog::new(CloseScope::Quit, title).document_wording(true));
// The question it replaced left a Cancel as its result; it was not answered, and the
// quit's question asks on.
let _ = self.framework_dialogs.take::<UnsavedChangesDialog>();
}
}
/// Reads the answer from an open [`UnsavedChangesDialog`] and continues closing or quitting.
pub(crate) fn take_unsaved_changes_dialog(&mut self, ctx: &egui::Context) {
let Some(result) = self.framework_dialogs.take::<UnsavedChangesDialog>() else {
return;
};
let Some(prompt) = self.unsaved_prompt.take() else {
return;
};
let answer = match result {
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::DontSave, .. }) => SaveAnswer::DontSave,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Save, .. }) => SaveAnswer::Save,
DialogResult::Ok(UnsavedAnswer { answer: CloseAnswer::Cancel, .. }) | DialogResult::Cancel | _ => SaveAnswer::Cancel,
};
if answer == SaveAnswer::Cancel {
return;
}
if let Some(w) = prompt.window.filter(|w| self.session.window(*w).is_some())
&& self.ui_window() != Some(w)
{
self.enter_window(w);
}
if self.session.active().map(|d| d.uid) != Some(prompt.doc) {
return;
}
if !self.answer_save_changes(answer, prompt.quitting, ctx) {
let title = self.session.active().map(|d| d.display_title()).unwrap_or_default();
let scope = if prompt.quitting { CloseScope::Quit } else { CloseScope::Close };
self.unsaved_prompt = Some(prompt);
self.framework_dialogs.open(UnsavedChangesDialog::new(scope, title).document_wording(true));
}
}
}
#[cfg(test)]
+1 -1
View File
@@ -258,7 +258,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) {
});
});
bs.text_edit_focused = ctx.text_edit_focused();
if !typing && !app.modal_open() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
if !typing && app.dialog.is_none() && app.message.is_none() && !egui::Popup::is_any_open(&ctx) && crate::framework::consume_escape(&ctx) {
out.close = true;
}
if let Some(page) = out.page {
-6
View File
@@ -46,12 +46,6 @@ pub(super) fn options(app: &mut SheetApp, ui: &mut Ui) {
}
}
ui.add_space(18.0);
section(ui, lang, "Display options for this worksheet");
let mut page_breaks = app.session.active().and_then(|d| d.wb.active().map(|s| s.show_page_breaks)).unwrap_or(false);
if ui.checkbox(&mut page_breaks, lang.tr("Show page breaks")).changed() {
app.run_or_alert("view.showPageBreaks", json!({"on": page_breaks}));
}
ui.add_space(18.0);
section(ui, lang, "Formulas");
ui.label(lang.tr("Workbook calculation"));
calc_options(app, ui, lang, &calc);
+3 -5
View File
@@ -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::{ChartLabels, HAlign, Prim, VAlign};
use gridcraft_chart::{HAlign, Prim, VAlign};
use gridcraft_engine::model::{Anchor, ObjKind, ObjRef, ShapeKind, Sheet, Workbook};
use crate::SheetApp;
@@ -39,8 +39,7 @@ 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 labels = ChartLabels { cumulative: crate::i18n::current(p.ctx()).tr("Cumulative %") };
let prims = gridcraft_chart::render_with_labels(chart, &data, w, h, &m, &labels);
let prims = gridcraft_chart::render(chart, &data, w, h, &m);
paint_prims(&p.with_clip_rect(rect.intersect(p.clip_rect())), origin, &prims, z);
}
@@ -255,8 +254,7 @@ 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 };
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)
gridcraft_chart::render(ch, &data, ch.anchor.width, ch.anchor.height, &m)
}
/// The primitives of chart `ci` of sheet `si`: from the frame cache when the workbook, zoom and
+2 -3
View File
@@ -147,8 +147,7 @@ pub fn inspect(app: &SheetApp, ctx: &egui::Context) -> Json {
"grid": app.grid.cells_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
"scroll": [v.scroll.x, v.scroll.y],
"editor": app.editor.as_ref().map(|e| editor_json(app, e)),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab}))
.or_else(|| app.unsaved_prompt.as_ref().map(|p| json!({"name": "saveChanges", "values": {"quit": p.quitting}}))),
"dialog": app.dialog.as_ref().map(|d| json!({"name": d.name, "title": d.title, "values": d.values, "tab": d.tab})),
"backstage": app.backstage.as_ref().map(|b| b.page.id()),
"message": app.message.as_ref().map(|(t, m)| json!({"title": t, "text": m})),
"selectedObject": app.selected_object,
@@ -340,7 +339,7 @@ pub fn handle(app: &mut SheetApp, ctx: &egui::Context, method: &str, p: &Json) -
}
"ui.dialog" => {
app.open_dialog(s("name").unwrap_or(""), p.clone());
ok(json!({"dialog": app.open_dialog_name()}))
ok(json!({"dialog": app.dialog.as_ref().map(|d| d.name.clone())}))
}
"ui.dialog.set" => match app.dialog.as_mut() {
Some(d) => {
+1
View File
@@ -1166,6 +1166,7 @@ impl Dialog {
"formatControl" => return crate::control_ui::open_format(app, &params),
"controlQuestion" => return crate::control_ui::open_question(&params),
"saveCopy" => Dialog::custom("saveCopy", "Save a Copy", json!({"format": p("format")})),
"saveChanges" => Dialog::custom("saveChanges", "Save Changes?", json!({"title": p("title"), "quit": p("quit")})),
"start" => Dialog::custom("start", "GridCraft", json!({})),
"comments" => {
app.grid.pane = None;
+2 -3
View File
@@ -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); 24] = [
const ALL_CHARTS: [(&str, &str, &str); 23] = [
("column", "", "Clustered Column"),
("column", "stacked", "Stacked Column"),
("column", "stacked100", "100% Stacked Column"),
@@ -23,7 +23,6 @@ const ALL_CHARTS: [(&str, &str, &str); 24] = [
("scatter", "lines", "Scatter with Lines"),
("radar", "", "Radar"),
("histogram", "", "Histogram"),
("pareto", "", "Pareto"),
("waterfall", "", "Waterfall"),
("funnel", "", "Funnel"),
("combo", "", "Combo"),
@@ -52,7 +51,7 @@ pub(super) fn select_chart(d: &mut Dialog, i: usize) {
fn chart_icon(t: &str) -> Icon {
match t {
"column" | "bar" | "histogram" | "pareto" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
"column" | "bar" | "histogram" | "waterfall" | "funnel" | "combo" => Icon::ChartBar,
"line" | "area" | "radar" => Icon::ChartLine,
"pie" | "doughnut" => Icon::ChartPie,
"scatter" | "bubble" => Icon::ChartScatter,
+13
View File
@@ -374,6 +374,19 @@ pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
}
}
}
"saveChanges" => {
ui.label(format!("Do you want to save the changes you made to {}?", d.values.get("title").and_then(Json::as_str).unwrap_or("this workbook")));
let quitting = d.values.get("quit").and_then(Json::as_bool) == Some(true);
ui.horizontal(|ui| {
for (label, answer) in
[("Don't Save", crate::SaveAnswer::DontSave), ("Cancel", crate::SaveAnswer::Cancel), ("Save", crate::SaveAnswer::Save)]
{
if ui.button(label).clicked() && app.answer_save_changes(answer, quitting, ui.ctx()) {
open = false;
}
}
});
}
"saveLoss" => {
let lang = app.ui.language;
let pending = d.pending_save();
+3 -3
View File
@@ -529,7 +529,7 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font:
let chars_before = ed.text.chars().count();
// A dialog opened over the edit (Paste Name) takes the keyboard until it closes, and the
// editor takes it back afterwards.
let dialog_open = app.modal_open();
let dialog_open = app.dialog.is_some();
if dialog_open && mine {
ed.request_focus = true;
ed.keep_selection = true;
@@ -671,7 +671,7 @@ fn editor_shortcuts(
) -> EditorKeyOutcome {
let mut outcome = EditorKeyOutcome { action: None, arrow: false, cancel: false, to_python: false };
// A message or dialog owns Enter and Escape until it closes.
if !has_focus || !mine || app.message.is_some() || app.modal_open() {
if !has_focus || !mine || app.message.is_some() || app.dialog.is_some() {
return outcome;
}
// Ctrl+Alt+Shift+P turns the edit into Python code.
@@ -864,7 +864,7 @@ fn python_editor(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, width: f32
let Some(mut ed) = app.editor.take() else { return EditorInfo::default() };
// A message box (the code was refused) or a dialog over the edit has the keyboard; the
// editor takes it back when it closes.
let blocked = app.message.is_some() || app.modal_open();
let blocked = app.message.is_some() || app.dialog.is_some();
let mut caret = None;
if blocked {
ed.request_focus = true;
-13
View File
@@ -112,22 +112,9 @@ impl SheetApp {
embed::logic(ctx, || self.close_decision(ctx));
}
/// Whether this pass draws [`SheetApp::framework_dialogs`]: the pass of the window the unsaved-changes
/// question asks about (the window that keeps it, as a GridCraft dialog stays in its window), else the root's.
/// `drawn` is the window the pass began drawing: a question a command in it opened for another window (a quit
/// moving on to the next unsaved workbook) shows in that window's own pass, not for a frame in this one.
pub(crate) fn framework_dialogs_here(&self, ctx: &egui::Context, drawn: Option<u64>) -> bool {
let shown = |w: &u64| self.session.window(*w).is_some_and(|w| !w.hidden);
match self.unsaved_prompt.as_ref().and_then(|p| p.window).filter(shown) {
Some(w) => drawn == Some(w),
None => ctx.viewport_id() == egui::ViewportId::ROOT,
}
}
/// The framework dialogs open on [`SheetApp::framework_dialogs`], once per frame after GridCraft's own UI.
pub(crate) fn run_framework_dialogs(&mut self, ui: &mut egui::Ui) {
self.framework_dialogs.run(ui);
self.take_unsaved_changes_dialog(ui.ctx());
}
}
-4
View File
@@ -19,8 +19,6 @@ use crate::theme::{self, Tokens};
pub(crate) type PaneQuad = ((u32, u32), (u32, u32), Rect);
/// Cached Page Break Preview ranges, keyed by (doc uid, revision, sheet).
type PagesCache = ((u64, u64, usize), Vec<(RangeRef, u32)>);
/// Cached Normal-view page breaks (row and column page bands), keyed by (doc uid, revision, sheet).
type PageBreaksCache = ((u64, u64, usize), Vec<(u32, u32)>, Vec<(u32, u32)>);
/// Cached Show Details cells, keyed by (doc uid, revision, sheet, pivot).
type DetailsCache = ((u64, u64, usize, usize), Option<std::collections::HashSet<(u32, u32)>>);
/// Cached fill-menu trend entries (label, mode), keyed by (doc uid, revision, sheet, source, dragged range).
@@ -380,8 +378,6 @@ pub struct GridState {
pub quick_analysis: crate::quick_analysis::State,
/// Page Layout view pagination, cached per (doc uid, revision, sheet, rows, columns).
pub paper: Option<crate::paper_view::PaperCache>,
/// Normal view's page breaks: row and column page bands, cached per (doc uid, revision, sheet).
pub page_breaks: Option<PageBreaksCache>,
/// Header or footer being edited in place (Page Layout view).
pub hf_edit: Option<crate::paper_view::HfEdit>,
/// A page margin being dragged on a ruler (Page Layout view); committed on release.
+1 -1
View File
@@ -19,7 +19,7 @@ fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response
// So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an
// arrow key would move the selection the menu fills from), and a macro's question.
editing
|| app.modal_open()
|| app.dialog.is_some()
|| other_focus
|| app.message.is_some()
|| app.grid.filter_menu.is_some()
+2 -2
View File
@@ -328,7 +328,7 @@ pub(super) fn fill_options_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo,
app.grid.fill_tag = None;
return;
}
if app.editor.is_some() || app.modal_open() || app.grid.drag != Drag::None {
if app.editor.is_some() || app.dialog.is_some() || app.grid.drag != Drag::None {
return;
}
let size = vec2(18.0, 18.0);
@@ -471,7 +471,7 @@ pub(super) fn object_menu(app: &mut SheetApp, ui: &mut egui::Ui) {
/// The warning button beside an active cell holding a number stored as text, as in Excel: its
/// menu names the problem and offers Convert to Number for the selection (#1994).
pub(super) fn error_check_tag(app: &mut SheetApp, ui: &mut egui::Ui, geo: &Geo, sh: &Sheet) {
if app.editor.is_some() || app.modal_open() || sh.show_formulas || app.grid.drag != Drag::None {
if app.editor.is_some() || app.dialog.is_some() || sh.show_formulas || app.grid.drag != Drag::None {
return;
}
let Some(active) = app.session.active().map(|d| d.selection.active) else { return };
-157
View File
@@ -200,8 +200,6 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) {
)
};
app.grid.cf = cf_sheet.map(|s| (s, cf));
// Page breaks sit on the cells, under objects and the selection, as in Excel.
paint_page_breaks(app, &painter.with_clip_rect(geo.cells), &geo, &wb, si, sh, &t);
// Objects above cells. A hidden object can't stay selected: Delete or the Format pane would act
// on something the user can't see.
if crate::chartview::objects_hidden(&wb) {
@@ -826,66 +824,6 @@ pub(crate) fn paint_overlays(input: OverlayInput<'_>) {
let _ = (wb, si);
}
/// Normal view with Show page breaks on: Excel's dashed lines where each page ends. The
/// pagination is the printing one (`layout_sheet`, no PDF), cached per (doc uid, revision, sheet)
/// and computed only while the lines are shown. Other views draw nothing here.
fn paint_page_breaks(app: &mut SheetApp, p: &Painter, geo: &Geo, wb: &Workbook, si: usize, sh: &Sheet, t: &Tokens) {
if sh.view != gridcraft_engine::model::SheetViewMode::Normal || !sh.show_page_breaks || geo.paper.is_some() {
return;
}
let Some(d) = app.session.active() else { return };
let key = (d.uid, d.revision, si);
if app.grid.page_breaks.as_ref().is_none_or(|(k, ..)| *k != key) {
use gridcraft_engine::cmd::print::{PrintOptions, layout_sheet, page_break_bands};
let bands = layout_sheet(wb, si, &PrintOptions::default(), None).map(|l| page_break_bands(sh, &l)).unwrap_or_default();
app.grid.page_breaks = Some((key, bands.0, bands.1));
}
let Some((_, rows, cols)) = &app.grid.page_breaks else { return };
let stroke = Stroke::new(1.0, t.page_break);
for seg in page_break_lines(sh, geo, rows, cols, p.clip_rect()) {
p.extend(egui::Shape::dashed_line(&seg, stroke, BREAK_DASH, BREAK_GAP));
}
}
const BREAK_DASH: f32 = 3.0;
const BREAK_GAP: f32 = 2.0;
/// The dashed lines of `paint_page_breaks`, in grid coordinates: one after the last column of
/// each page column and one after the last row of each page row, across the printed extent.
/// The final band has been extended to its page capacity for the editing overlay. A
/// line scrolled under a frozen pane is left out, and the extent starts below / right of the
/// frozen panes when the printed cells do. Lines are cut to `clip` (a dashed line costs a shape
/// per dash, and the extent of a long list is far taller than the screen); a cut start moves to
/// the next dash boundary of the whole line, so the dashes don't crawl while scrolling.
fn page_break_lines(sh: &Sheet, geo: &Geo, rows: &[(u32, u32)], cols: &[(u32, u32)], clip: Rect) -> Vec<[egui::Pos2; 2]> {
let (Some(r0), Some(r1), Some(c0), Some(c1)) = (rows.first(), rows.last(), cols.first(), cols.last()) else { return vec![] };
let pane_top = geo.cells.top() + geo.frozen_h;
let pane_left = geo.cells.left() + geo.frozen_w;
let period = BREAK_DASH + BREAK_GAP;
// The first dash boundary of the whole line at or past `edge`.
let cut = |start: f32, edge: f32| if start < edge { start + ((edge - start) / period).ceil() * period } else { start };
let top = cut(geo.y(sh, r0.0), if r0.0 >= geo.fr { pane_top.max(clip.top()) } else { clip.top() });
let left = cut(geo.x(sh, c0.0), if c0.0 >= geo.fc { pane_left.max(clip.left()) } else { clip.left() });
let frozen_bottom = if r0.0 < geo.fr { geo.y_end(sh, r1.1.min(geo.fr - 1)) } else { f32::NEG_INFINITY };
let frozen_right = if c0.0 < geo.fc { geo.x_end(sh, c1.1.min(geo.fc - 1)) } else { f32::NEG_INFINITY };
let bottom = geo.y_end(sh, r1.1).max(frozen_bottom).min(clip.bottom());
let right = geo.x_end(sh, c1.1).max(frozen_right).min(clip.right());
let mut out = Vec::new();
for &(_, last) in cols {
let x = geo.x_end(sh, last);
if (last < geo.fc || x >= pane_left) && (clip.left()..=clip.right()).contains(&x) && bottom > top {
out.push([pos2(x, top), pos2(x, bottom)]);
}
}
for &(_, last) in rows {
let y = geo.y_end(sh, last);
if (last < geo.fr || y >= pane_top) && (clip.top()..=clip.bottom()).contains(&y) && right > left {
out.push([pos2(left, y), pos2(right, y)]);
}
}
out
}
fn paint_pages(app: &mut SheetApp, p: &Painter, geo: &Geo, sh: &Sheet) {
let Some(d) = app.session.active() else { return };
let key = (d.uid, d.revision, d.wb.active_sheet());
@@ -1220,98 +1158,3 @@ mod trace_arrow_tests {
assert!((30..=60).contains(&further.len()), "{}", further.len());
}
}
#[cfg(test)]
mod page_break_tests {
use super::*;
use gridcraft_engine::model::{DEFAULT_COL_WIDTH, DEFAULT_ROW_HEIGHT};
/// Two pages across and two down, with a hidden row inside the first page row: the lines sit
/// after columns E and J and after rows 10 and 20, and the hidden row takes no height.
#[test]
fn page_breaks_follow_the_page_bands_in_both_directions() {
let mut sh = Sheet::new("S");
sh.rows.entry(4).or_default().hidden = true;
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 0.0));
let (x0, y0, z) = (geo.cells.left(), geo.cells.top(), geo.z);
let (w, h) = (DEFAULT_COL_WIDTH * z, DEFAULT_ROW_HEIGHT * z);
let lines = page_break_lines(&sh, &geo, &[(0, 9), (10, 19)], &[(0, 4), (5, 9)], geo.cells);
let (bottom, right) = (y0 + 19.0 * h, x0 + 10.0 * w);
let expect = [
[pos2(x0 + 5.0 * w, y0), pos2(x0 + 5.0 * w, bottom)],
[pos2(right, y0), pos2(right, bottom)],
[pos2(x0, y0 + 9.0 * h), pos2(right, y0 + 9.0 * h)],
[pos2(x0, bottom), pos2(right, bottom)],
];
assert_eq!(lines.len(), expect.len(), "{lines:?}");
for (got, want) in lines.iter().zip(expect) {
for (g, w) in got.iter().zip(want) {
assert!((g.x - w.x).abs() < 0.01 && (g.y - w.y).abs() < 0.01, "{lines:?}");
}
}
assert!(page_break_lines(&sh, &geo, &[], &[(0, 4)], geo.cells).is_empty(), "no pages, no lines");
}
/// Frozen rows: a page break scrolled up under them is not drawn over the frozen rows, and the
/// vertical lines start below them.
#[test]
fn page_breaks_scrolled_under_frozen_rows_are_hidden() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 0));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 10.0 * DEFAULT_ROW_HEIGHT));
let pane_top = geo.cells.top() + geo.frozen_h;
let lines = page_break_lines(&sh, &geo, &[(5, 9), (10, 40)], &[(5, 9)], geo.cells);
let horizontal: Vec<_> = lines.iter().filter(|l| l[0].y == l[1].y).collect();
assert_eq!(horizontal.len(), 1, "the break after row 10 is under the frozen rows: {lines:?}");
assert!(horizontal[0][0].y > pane_top);
let vertical: Vec<_> = lines.iter().filter(|l| l[0].x == l[1].x).collect();
assert_eq!(vertical.len(), 1);
let start = vertical[0][0].y;
assert!(start >= pane_top && start < pane_top + BREAK_DASH + BREAK_GAP, "starts below the frozen rows: {start} vs {pane_top}");
}
#[test]
fn page_break_at_freeze_boundary_stays_on_frozen_edge() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 2));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(200.0, 200.0));
let lines = page_break_lines(&sh, &geo, &[(0, 2)], &[(0, 1)], geo.cells);
assert!(lines.iter().any(|line| line[0].y == geo.cells.top() + geo.frozen_h && line[1].y == line[0].y));
assert!(lines.iter().any(|line| line[0].x == geo.cells.left() + geo.frozen_w && line[1].x == line[0].x));
}
#[test]
fn scrolled_past_print_extent_keeps_frozen_portion_of_breaks() {
let mut sh = Sheet::new("S");
sh.freeze = Some((3, 2));
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 1000.0)), vec2(2000.0, 2000.0));
let lines = page_break_lines(&sh, &geo, &[(0, 1), (2, 9)], &[(0, 0), (1, 9)], geo.cells);
assert!(lines.iter().any(|line| line[0].x == line[1].x && line[1].y >= geo.cells.top() + geo.frozen_h));
assert!(lines.iter().any(|line| line[0].y == line[1].y && line[1].x >= geo.cells.left() + geo.frozen_w));
}
/// A 100,000-row print extent scrolled to its middle: every line is cut to the visible cells
/// (a dashed line is one shape per dash), and the cut keeps the dash phase of the whole line.
#[test]
fn page_breaks_are_cut_to_the_visible_cells() {
let sh = Sheet::new("S");
let geo = Geo::new(&sh, Rect::from_min_size(pos2(0.0, 0.0), vec2(2000.0, 2000.0)), vec2(0.0, 50_001.0 * DEFAULT_ROW_HEIGHT));
let rows: Vec<(u32, u32)> = (0..2000).map(|i| (i * 50, i * 50 + 49)).collect();
let lines = page_break_lines(&sh, &geo, &rows, &[(0, 4), (5, 9)], geo.cells);
let horizontal = lines.iter().filter(|l| l[0].y == l[1].y).count();
assert!(horizontal > 0 && horizontal < 10, "only the breaks on screen: {horizontal}");
assert_eq!(lines.len() - horizontal, 2);
for l in &lines {
for pt in l {
assert!(geo.cells.expand(BREAK_DASH + BREAK_GAP).contains(*pt), "{pt:?} outside {:?}", geo.cells);
}
}
let full_top = geo.y(&sh, 0);
let vertical = lines.iter().find(|l| l[0].x == l[1].x).unwrap();
// 50,001 rows above at 16 px each put the view's top 1 px past a dash boundary of the whole
// line: the cut line starts at the next boundary, 4 px down (`max` would start it at the top).
assert!((vertical[0].y - (geo.cells.top() + 4.0)).abs() < 0.15, "{:?} vs {}", vertical[0], geo.cells.top());
let phase = (vertical[0].y - full_top) % (BREAK_DASH + BREAK_GAP);
assert!(phase.abs() < 0.15 || (BREAK_DASH + BREAK_GAP - phase).abs() < 0.15, "phase {phase}");
}
}
-1
View File
@@ -171,7 +171,6 @@ fn filter_menu_uses_the_table_whose_header_was_clicked() {
filter: vec![],
table_type: None,
connection_id: None,
query_table: None,
};
let mut sh = Sheet::new("S");
sh.tables.push(table(1, 0, 2));
-2
View File
@@ -430,8 +430,6 @@ 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",
-2
View File
@@ -447,8 +447,6 @@ 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",
+3 -2
View File
@@ -393,8 +393,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "Αυτοματισμός",
"Table Design" => "Σχεδίαση πίνακα",
"Chart Design" => "Σχεδίαση γραφήματος",
"Pareto" => "Παρέτο",
"Cumulative %" => "Αθροιστικό %",
"Ready" => "Έτοιμο",
"Enter" => "Εισαγωγή",
"Edit" => "Επεξεργασία",
@@ -574,6 +572,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Zoom Out" => "Σμίκρυνση",
"Dismiss" => "Κλείσιμο",
"OK" => "Εντάξει",
"Don't Save" => "Χωρίς αποθήκευση",
"Open…" => "Άνοιγμα…",
"Show password" => "Εμφάνιση κωδικού πρόσβασης",
"Start a new workbook" => "Δημιουργία νέου βιβλίου εργασίας",
@@ -582,6 +581,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Βαθμολόγιο",
"this workbook" => "αυτό το βιβλίο εργασίας",
"This workbook" => "Αυτό το βιβλίο εργασίας",
"Do you want to save the changes you made to {title}?" => "Θέλετε να αποθηκεύσετε τις αλλαγές που κάνατε στο {title};",
"Save a copy as .{format}" => "Αποθήκευση αντιγράφου ως .{format}",
"Select a chart first." => "Επιλέξτε πρώτα ένα γράφημα.",
"Row Height" => "Ύψος γραμμής",
@@ -622,6 +622,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Τοποθέτηση εικόνας πάνω από κελιά",
"Pick From List" => "Επιλογή από λίστα",
"Save a Copy" => "Αποθήκευση αντιγράφου",
"Save Changes?" => "Αποθήκευση αλλαγών;",
"Shift cells right" => "Μετατόπιση κελιών προς τα δεξιά",
"Shift cells down" => "Μετατόπιση κελιών προς τα κάτω",
"Shift cells left" => "Μετατόπιση κελιών προς τα αριστερά",
-2
View File
@@ -434,8 +434,6 @@ 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",
-2
View File
@@ -308,8 +308,6 @@ 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",
+3 -2
View File
@@ -292,8 +292,6 @@ 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",
@@ -445,6 +443,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Calculation settings are saved with the workbook." => "Le impostazioni di calcolo vengono salvate con la cartella di lavoro.",
"OK" => "OK",
"Cancel" => "Annulla",
"Don't Save" => "Non salvare",
"Open…" => "Apri…",
"Show password" => "Mostra password",
"Start a new workbook" => "Crea una nuova cartella di lavoro",
@@ -453,6 +452,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Gradebook" => "Registro dei voti",
"this workbook" => "questa cartella di lavoro",
"This workbook" => "Questa cartella di lavoro",
"Do you want to save the changes you made to {title}?" => "Vuoi salvare le modifiche apportate a {title}?",
"Save a copy as .{format}" => "Salva una copia come .{format}",
"Select a chart first." => "Seleziona prima un grafico.",
"Text Box" => "Casella di testo",
@@ -503,6 +503,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Place Picture over Cells" => "Inserisci immagine sopra le celle",
"Pick From List" => "Scegli dall'elenco",
"Save a Copy" => "Salva una copia",
"Save Changes?" => "Salvare le modifiche?",
"Shift cells right" => "Sposta celle a destra",
"Shift cells down" => "Sposta celle in basso",
"Shift cells left" => "Sposta celle a sinistra",
+3 -2
View File
@@ -299,8 +299,6 @@ pub(super) const CORE: &[(&str, &str)] = &[
("Automate", "自動化"),
("Table Design", "テーブル デザイン"),
("Chart Design", "グラフ デザイン"),
("Pareto", "パレート図"),
("Cumulative %", "累積 %"),
("Ready", "準備完了"),
("Enter", "入力"),
("Edit", "編集"),
@@ -462,6 +460,7 @@ pub(super) const CORE: &[(&str, &str)] = &[
pub(super) const DIALOGS: &[(&str, &str)] = &[
("OK", "OK"),
("Cancel", "キャンセル"),
("Don't Save", "保存しない"),
("Open…", "開く…"),
("Show password", "パスワードの表示"),
("Start a new workbook", "新しいブックの作成"),
@@ -470,6 +469,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Gradebook", "成績表"),
("this workbook", "このブック"),
("This workbook", "このブック"),
("Do you want to save the changes you made to {title}?", "{title} への変更を保存しますか?"),
("Save a copy as .{format}", ".{format} としてコピーを保存"),
("Select a chart first.", "先にグラフを選択してください。"),
("Text Box", "テキスト ボックス"),
@@ -520,6 +520,7 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[
("Place Picture over Cells", "セルの上に画像を配置"),
("Pick From List", "リストから選択"),
("Save a Copy", "コピーを保存"),
("Save Changes?", "変更を保存しますか?"),
("Shift cells right", "セルを右に移動"),
("Shift cells down", "セルを下に移動"),
("Shift cells left", "セルを左に移動"),
-2
View File
@@ -293,8 +293,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> {
"Automate" => "자동화",
"Table Design" => "표 디자인",
"Chart Design" => "차트 디자인",
"Pareto" => "파레토",
"Cumulative %" => "누적 %",
"Ready" => "준비",
"Enter" => "입력",
"Edit" => "편집",
-2
View File
@@ -299,8 +299,6 @@ 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",

Some files were not shown because too many files have changed in this diff Show More