Compare commits

..
Author SHA1 Message Date
FredApps 687ecd3a12 Save the Firefox result through the focused GTK filename field 2026-12-02 22:20:46 +01:00
FredApps 0f8a55b580 Recognize the Firefox GTK file chooser from its visible controls 2026-12-02 22:14:35 +01:00
FredApps ee8f7a5668 Exercise the shared PDF print action in a real Firefox preview 2026-12-02 22:08:34 +01:00
FredApps 47055d4f58 Exercise browser cancellation and save the next PDF in the same session 2026-12-02 22:04:58 +01:00
FredApps 73da9c65c8 Capture and inspect consecutive PDF jobs from the shared browser printer 2026-12-02 21:59:59 +01:00
FredApps 71ec2b9aa0 Use craft-print for GridCraft web printing
Stage this switch until the shared browser lifecycle patch is included in the unified craft-libs pin and verified with browser PDF viewers.
2026-12-02 20:15:48 +01:00
FredApps a4d025e778 Merge pull request #4965 from Terra854/fix/issue-3673
XLSX: split overlong scalar text literals on save (#3673)
2026-12-02 19:57:20 +01:00
FredApps 79c31a6a9f Merge pull request #2328 from nihilist-narwhal/fix/2160-validate-json-workbook
JSON workbooks: loaded ranges are ordered and on the sheet, damaged arrays are dropped (#2160)
2026-12-02 11:00:25 +01:00
MaciekandMaciej Malinowski 80e5bf2857 formula: Polish formula language (FormulaLocale::Pl) (#1883)
* formula: Polish formula language (FormulaLocale::Pl)

- FormulaLocale::Pl: all 434 functions whose Polish Excel name differs, in
  crates/formula/src/input/pl.rs. Names come from PhpSpreadsheet's pl table
  (MIT) cross-checked with a second independent table; where they disagree
  or are missing, Microsoft's pl-pl pages decide, and the names #1678
  observed in Excel for the web fill the rest. Polish keeps MAX (only
  MAXIFS is MAKS.WARUNKÓW).
- PRAWDA/FAŁSZ, `;` argument and `\` array-column separators, decimal comma.
- Polish error values on entry and display (#DZIEL/0!, #N/D, #ARG!,
  #ROZLANIE!, #OBL!...); #N/D! and English spellings stay accepted.
- Table specifiers (#Wszystko, #Dane, #Nagłówki, #Sumy, #Ten wiersz) with
  ';' between bracketed parts.
- The locale tables are generalised (aliases()/boolean_names()) instead of
  hard-coding Spanish, and the parser keeps the locale instead of an `Es`
  flag; names are compared with the shared same_name, so `jeżeli` matches
  `JEŻELI` and a LET name `fałsz` is matched by `FAŁSZ`. Spanish behaviour
  is unchanged.
- Function help follows the interface language, as on main: Polish
  descriptions and argument names belong to the Polish catalog (#1807).
- Tests: crates/formula/tests/polish_input.rs and
  crates/calc/tests/polish_function_names.rs (every Polish name belongs to a
  known function and none shadows an English one).
- Docs: ROADMAP.md and docs/localization-parity.md.

The Polish interface language (on main since #1091) selects the locale:
Language::formula_locale maps Pl to it.

* formula: credit PhpSpreadsheet for the Polish function name table

The English-to-Polish name table in crates/formula/src/input/pl.rs comes
from PhpSpreadsheet's locale/pl/functions (MIT). ATTRIBUTION.md now lists
it in the same form as the CLDR region data, and NOTICE carries
PhpSpreadsheet's MIT licence text verbatim. The second table the names
were checked against was only a cross-check, and nothing was copied from
it; the module comment now says so.

---------

Co-authored-by: Maciej Malinowski <[email protected]>
2026-12-02 10:11:27 +01:00
NetterSilverandSilvertree2010 52276ad881 Function Arguments dialog: one box per argument with live values (fx, Shift+F3) (#4538)
* Function Arguments: one box per argument with live values (#4322)

Insert Function OK, fx and Shift+F3 open a Function Arguments dialog: a box per argument from the function signature (optional ones not bold, repeating ones growing as they are filled), each box's value, the function and formula results, and per-argument descriptions for the common functions. Shift+F3 inside a call, or fx on a formula cell, opens it with the call's arguments filled in.

* Function Arguments: keep draft out of grid commits, keep given blanks, key preview by cell, stay open on refusal

* Function Arguments: show argument help through the translation catalog, key the preview cache by revision

* i18n-report: inventory the per-argument help strings as translation keys

* i18n-report: list every per-argument help key

---------

Co-authored-by: Silvertree2010 <[email protected]>
2026-12-02 10:09:05 +01:00
FredApps 7f8a981d8a Merge main into fix/2160-validate-json-workbook 2026-12-02 09:12:39 +01:00
FredApps 9d00fe9cca Merge pull request #259 from AlissonFA/feat/table-auto-expansion
engine: table auto-expansion on adjacent row and column edits (#258)
2026-12-02 09:03:51 +01:00
FredApps 4e8d4f2d80 Merge pull request #249 from MacJedi42/fix/excel-snap-to-zero
Accuracy: Excel's snap to zero at a formula's root, in SUM, in names and in LAMBDA bodies
2026-12-02 09:03:21 +01:00
FredApps 505e303d13 Merge main into fix/2160-validate-json-workbook 2026-12-02 07:05:12 +01:00
FredApps 4434e3bd05 Merge main into feat/table-auto-expansion 2026-12-02 07:05:01 +01:00
FredApps 7960441bca Merge main into fix/excel-snap-to-zero 2026-12-02 07:04:56 +01:00
FredApps a09cd4fa30 Merge pull request #1816 from azislamayuda/fix/linux-titlebar-adwaita
#54: fix Linux Wayland title bar and Clippy warnings
2026-12-02 06:50:22 +01:00
FredApps 3547cd1593 Merge main into fix/linux-titlebar-adwaita
# Conflicts:
#	Cargo.lock
2026-12-02 11:57:57 +07:00
FredApps e605ad4e69 Merge pull request #4986 from storytold/yan/fix-main-quick-xml-042
Fix main: xlsx passthrough reads quick-xml 0.42 names and values as &str
2026-12-02 05:57:27 +01:00
FredApps 4eb8e3e38d Fix main: xlsx passthrough reads quick-xml 0.42 names and values as &str 2026-12-02 11:22:23 +07:00
FredApps d176602488 Merge pull request #3407 from alosslessdev/dax/eval-aggregation
dax: aggregation, logical, information and model-info functions (#2228)
2026-12-02 00:43:18 +01:00
FredApps 14493aa259 Merge pull request #2665 from Harrison-Booth/gc-fix-deps
Dependencies: quick-xml 0.41 to 0.42 (xlsx reads names and values as &str)
2026-12-02 00:42:52 +01:00
FredApps d4ef6064a4 Merge pull request #2365 from MarekSpodBiedry/issue-2333
Print text that overflows out of the last used column in PDF export (#2333)
2026-12-02 00:42:27 +01:00
Terra854 60c72b77a6 XLSX: split overlong scalar text literals on save (#3673) 2026-12-01 21:34:22 +08:00
Aleksander HelgakerandClaude Opus 5.5 226a5d3d26 Print: sheets left out of whole-workbook printing (ODS groundwork) (#4104)
* Print: sheets left out of whole-workbook printing

PrintSettings gains `excluded` (serde default false, not written when
false). Printing or exporting the whole workbook (`sheets: all`) skips a
sheet marked excluded, unless every visible sheet is, in which case they
all print, as LibreOffice does with an OpenDocument sheet set not to
print (`table:print="false"`). Printing the active sheet alone is
unaffected. `pageLayout.pageSetup {excluded: bool}` sets it, in one undo
step with the rest of Page Setup.

Excel has no such flag, so XLSX neither reads nor writes it.

* Print: excluded active sheet is not the blank fallback; explicit range prints

Review follow-up. With `sheets: all`, when every printable sheet was
blank the fallback page came from the active sheet even if it was left
out of workbook printing; it now comes from the active sheet only when
that sheet would print, else the first sheet that would. A `range` given
for the active sheet is asked for explicitly, so that sheet prints even
when excluded (it was silently dropped).

* Print: every sheet excluded prints them all, also with a range

Review follow-up. With `sheets: all` and a `range`, the range exception
kept the active sheet among the printed ones, so the "every visible
sheet is excluded, all print" rule never applied and only the active
sheet printed. That rule is now decided first.

* Save: ask before XLSX drops a sheet's print exclusion, and report it

XLSX can't hold PrintSettings::excluded, and Save and Save As dropped it
silently. A save from the interface now asks first and offers a GridCraft
workbook (.json), AutoSave waits for that answer, and file.save,
file.saveAs and file.saveBytes return what was lost as `warnings`, which
the CLI prints. Saves that lose nothing are unchanged.

* Save question: one pending save says what was asked, by which workbook, and what follows

The question about what a save would lose kept loose dialog values and
acted on whatever was active when it was answered. It now holds one
PendingSave: the workbook that asked, the save as it was run, exactly
which sheets lose something, and the close or quit that waits for it.

- Save As with no path is asked about the file that is picked, so it
  never writes the workbook's own file.
- Another workbook is never saved or agreed to; ui.dialog.set can't
  change the save behind the question.
- Agreeing is to the sheets themselves, not to the text that names some.
- A question that replaces another takes its close and quit along.

* AutoSave: the hold notice goes when the hold ends

The hold lasts while AutoSave is on and the workbook has changes whose
loss was not agreed to. When it ends, its notice and its entry go, so a
later hold on the same sheets is said again. Other notices stay.

* CLI: print file.saveBytes warnings too

Review follow-up. `file.saveBytes` returns `warnings` like Save and
Save As, but the CLI printed only theirs, so `run --quiet` with a
saveBytes command hid what the .xlsx encoding lost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Save loss: ask again when the workbook's file changed meanwhile

A held plain Save took the workbook's path when answered, so if the file
changed while the question was open, Save Anyway wrote a file nobody was
asked about. The question now records the file it is about and asks again
for the new one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 11:29:43 +01:00
Aleksander HelgakerandFredApps 585970c542 formula: printer dialects and parsing from tokens (ODS groundwork) (#4135)
* formula: printer dialects and parsing from tokens

A `Dialect` trait states how another formula syntax spells references,
names, structured references, functions, booleans, separators, operators
and operator-less unary forms; `print_with(&Expr, &dyn Dialect)` prints
through it. `print` and `print_r1c1` are the A1 and R1C1 dialects, so
Excel output is byte-for-byte unchanged.

`parse_tokens(Vec<Token>)` builds an `Expr` from another tokenizer's
tokens with this grammar (capped at MAX_FORMULA_LEN tokens), and
`Tok::Ref` carries a reference that tokenizer has already read.

Groundwork for reading and writing OpenFormula in ODS files.

* formula: bound parse_tokens input like text; document Dialect methods

parse_tokens refuses a Tok::Ref off the grid (rows or columns past
Excel's limits) and token text (strings, names, sheet names, structured
bodies) longer than MAX_FORMULA_LEN in all, as formula text is bounded.
Range ends keep their order, as the text parser keeps `B2:A1`. The doc
says OpenFormula's `~` union is not read here.

Tok is #[non_exhaustive] now that other tokenizers can need new kinds;
no match outside the crate is exhaustive. Dialect::boolean, separators
and operator have doc comments.

* formula: parse_tokens refuses non-finite numbers, early Eof, empty sheets

A Tok::Number that is NaN or infinite is refused as the A1 lexer refuses
it (it printed as `0`, changing the value). An Eof before the last token
is an error instead of silently dropping what follows. A sheet name in a
Tok::Ref or Tok::Sheet may not be empty.

* formula: parse_tokens refuses words the A1 tokenizer would not read

A Tok::Word or Tok::Func must be what the A1 tokenizer reads from its
text (re-lexed and compared): an empty one, or `A!1`, `TRUE`, `a b`,
printed as text that would not parse back. An empty structured
reference body stays accepted: text reads `[]` the same way. Tests also
cover an empty second sheet name in Tok::Sheet.

* formula: parse_tokens refuses trees that would not print back; nesting bound as text

Review round fixes (after merging main):
- Apply main's whole-tree wrapper-height bound (#3813) to parse_tokens through a
  shared finish step; a token stream of stacked `(..)%%%` levels was accepted.
- Drop spaces that are not between two operands, as text does; `Tok::Ref` now
  counts as an operand for the intersection.
- Refuse negative numbers (`-1` reads back as a negation), sheet names holding
  `:` (they read back as a span), `Tok::Trim` (no OpenFormula form, and most
  shapes have no text form), and a word directly before `(`.
- The TRIMRANGE fallback is named through `Dialect::function`.

* formula: parse_tokens checks that the tree prints back as itself

Second review round. Correcting the first round's piecemeal checks, which
missed operands of `:` that regroup or change kind when printed:
`A1` `:` `B2:C3` printed as `A1:B2:C3` (read back as `(A1:B2):C3`), a
sheet-qualified right side read back as a 3-D span, `1` `:` `3` read back
as rows, and a row range before an intersection space printed text that
does not parse.

parse_tokens now prints the tree and parses that text back, refusing the
tokens unless the same tree returns. Numbers are compared as they print
(15 significant digits), so a longer literal is still read as given. The
earlier checks stay for their precise messages. The printed text is
bounded as typed text is, so a string that fits only without its quotes is
refused.

---------

Co-authored-by: FredApps <[email protected]>
2026-12-01 11:21:16 +01:00
gmrmad1 9ed28ba9ea functions: XIRR rejects a Boolean guess (#4045) (#4251) 2026-12-01 11:11:41 +01:00
Aleksander HelgakerandClaude Opus 5.5 4d94d3e27c Data: paste or import clipboard text as columns (Get Data › From Clipboard…, Paste Data…) (#4839)
* feat(data): paste or import clipboard text as columns

Data › Get Data (Text/CSV) becomes a split button. Its menu adds
From Clipboard…, and the cell menu adds Paste Data… after Paste
Special…. Both open a dialog that asks for the separator (comma,
semicolon, tab, space or another character), starting on the one the
text uses. From Clipboard imports into a new sheet as a table, and
Paste Data pastes the columns at the clicked cell. The dialog imports
the text it read when it opened, and Paste Data names the sheet with
its cell.

- data.fromTextCsv: `at` pastes at a cell, Sheet!-qualified or on the
  active sheet. Without a delimiter, craft-csv's sniffer picks comma,
  semicolon or tab. JSON records are read only when no delimiter is
  given. The delimiter must be one character other than a quote or
  line break, up to U+00FF. The reader's cells are written with their
  number formats, so dates and percents keep them and formula-looking
  text stays text.
- data.fromClipboard (UI command): the same with the system clipboard.
- Key tips: Alt/F10, A, P, N opens the Get Data menu with G and C
  (APNC is new). Up/Down in a menu key tips opened moves focus onto
  its items, wrapping at the ends. Enter runs the focused item without
  also confirming what it opens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(data): clipboard import review fixes and rustfmt

- Paste Data's destination is a "Paste at" reference box holding the
  selection's top-left cell, the cell Paste uses. As in the other
  dialogs with reference boxes, OK shows the dialog's own sheet again
  first, found by its uid, and is refused once that sheet is deleted.
- A paste at a cell covers every field of the text, trailing blank
  fields and records included, so they clear the cells under them.
  read_csv_with_report now reports the record count and the widest
  record.
- CSV dates are read as serials of the destination workbook's date
  system (1900 or 1904).
- The first arrow into a key-tip menu cancels the focus move egui had
  already queued, so it lands on the first item even when a ribbon
  button was focused.
- cargo fmt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(data): Paste Data refuses rows past the sheet and clears all-blank text

- read_csv_with_report reports `truncated` when the text has records
  past a sheet's last row. A paste at a cell refuses such text before
  writing anything, instead of dropping the rest. Text with exactly
  MAX_ROWS records still pastes.
- A paste at a cell uses the text's record extent even when it has no
  non-empty field, so text like `,` clears the cells it covers instead
  of failing as an empty file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(data): Paste Data refuses text wider than a sheet

The CSV reader keeps one field past MAX_COLS per record, so a wider
record can be told from one that fits, and reports it as `truncated`,
as it does records past the last row. A paste at a cell refuses such
text before writing anything; text exactly MAX_COLS fields wide still
pastes. Importing into a new sheet still keeps the first MAX_COLS
fields, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(data): read bracket-led text without a separator as delimited text

From Text/CSV, Get Data and From Clipboard read any text whose first
character is `[` as JSON when no separator was given, so delimited text
whose first field is bracketed (`[Draft];Oslo`) was rejected with a JSON
parse error. Text is now read as records only when it parses as a JSON
array of objects; anything else goes to the delimited reader, which picks
the separator by the text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 10:54:16 +01:00
Dylan M. Taylor 9a1e05f442 ci(sonarcloud): give each main commit its own concurrency group (#4912) 2026-11-29 18:47:35 -05:00
Dylan M. Taylor be7732912b ci(nightly): enable automated scheduled nightly builds and Stage 2 signer dispatch (#4881)
* ci(nightly): enable scheduled nightly builds and automatic signer dispatch

* ci: update actions lockfile for nightly-dispatch.yml

* test(packaging): read workspace version from Cargo.toml in Linux launch test
2026-11-29 18:26:46 -05:00
Dylan M. Taylor c869fdb23c test(nightly): preserve startup failure without stable fallback (#4911) 2026-11-29 15:12:20 -05:00
Your New Name d0661f8505 dax: keep native Integer operands exact in BITAND, BITOR and BITXOR (#2228) 2026-11-29 14:25:06 -05:00
Dylan M. Taylor be07bd69fd feat(nightly): wire craft-nightly for self-isolated nightly launches (#4906) 2026-11-29 13:48:48 -05:00
BFlat 5f22c7c01c Merge pull request #4908 from ruchirguitar/gc-4131-indic-fonts
Indian-script fallback fonts: Gujarati and Hindi text draws instead of boxes
2026-11-30 01:21:46 +07:00
ruchirguitar 838c9104c0 docs: one script-fallback paragraph in localization-parity.md
Drops the repeated Lao list and the stale 'no complex-text shaping'
sentence, which contradicted the Indian-script text.
2026-11-29 21:26:35 +05:30
ruchirguitar ade107ab73 fonts: name the Indian-script face tuple type (clippy type_complexity) 2026-11-29 21:15:45 +05:30
ruchirguitarandkulveersingh 44b8fc5b52 fonts: Indian-script shaping test accepts a ligated split vowel; docs
Nirmala UI draws Tamil கொ as one ligature rather than the vowel sign on
both sides of க, which is also shaped. The test now fails only when the
text comes out one glyph per code point. localization-parity.md lists
the Indian-script fallback faces and no longer says Devanagari is
unshaped.

Fixes #4131.

Co-authored-by: kulveersingh <[email protected]>
2026-11-29 21:09:57 +05:30
kulveersingh 331486148e fonts: system fallback faces for the nine Indian scripts
Gujarati, Hindi (Devanagari) and the other Indian scripts showed as empty
boxes in cells and the interface: the default fonts (Calibri, Arial) have
no glyphs for them and the fallback chain had no Indian-script face.

Adds one fallback entry per script, probing the system's own fonts:
Nirmala UI and the per-script faces on Windows, Kohinoor, Noto and
Sangam MN on macOS (the Regular face inside each collection), Noto Sans
or Lohit on Linux and the BSDs, including Fedora's variable Noto faces
and a Flatpak's host font mounts. Nothing is bundled.

From storytold/gridcraft#581 (17328a73d, 789311da8), ported to the
theme/font_fallback.rs layout on main.
2026-11-29 21:09:34 +05:30
AlissonFAandClaude Opus 5.5 28bd4b42d0 #258: the formula-header Resize Table test enters its formula away from the table
The test typed =1+1 next to the table's header row, which now grows the table
and names the column itself, so table.resize had nothing left to do and the
test no longer reached Resize Table's own header naming. The formula now goes
in D1, two columns away, and the test checks the table did not grow before
the resize.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 07:18:32 -03:00
FredAppsandFredrik Hallin 684d86b78d Release: GridCraft v0.20.0 (#4897)
Co-authored-by: Fredrik Hallin <[email protected]>
2026-11-29 04:44:17 +01:00
Dylan M. Taylor 5b43c2abc8 fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#4896) 2026-11-28 22:40:36 -05:00
Dylan M. Taylor 01c94182f5 ci: pin storytold/craft-common-actions to @main universally (#4889) 2026-11-28 16:06:32 -05:00
Dylan M. Taylor 0ff6f02485 ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#4887) 2026-11-28 15:21:23 -05:00
Dylan M. Taylor f2934fd009 fix(nightly): allow reopening nightly profile with saved settings and session files (#4872) 2026-11-28 11:41:01 -05:00
FredApps ba597305a1 Merge pull request #4140 from alehel/split/text-defaults
Model: workbook text defaults: languages, Asian and complex fonts (ODS groundwork)
2026-11-27 23:29:47 +01:00
FredApps 0e57a9d37d rustfmt the lambda snap_root tail steps after merging main 2026-11-28 05:28:19 +07:00
FredApps b15dde1795 Compare SUM in the range-fold test to a last-addition snap, not a plain fold 2026-11-28 05:17:23 +07:00
FredApps b742816737 parity: headless column from the engine registry (RFC-0052) (#4860) 2026-11-27 23:14:07 +01:00
FredApps 2b71cf261f Don't use range_sum for SUM/AVERAGE so the last addition still snaps 2026-11-28 05:07:58 +07:00
FredApps 500f380504 Fix Acc privacy and enter() Result type after merging main 2026-11-28 05:02:31 +07:00
FredApps a608301540 Merge main into fix/excel-snap-to-zero
# Conflicts:
#	crates/calc/src/eval/array.rs
#	crates/calc/src/eval/call.rs
#	crates/calc/src/eval/lambda.rs
2026-11-28 04:57:06 +07:00
skylar taylor-barrick 97f2754c1d nightly: put macOS notices where Launcher expects them (#4851) 2026-11-27 18:56:30 +01:00
skylar taylor-barrick 6357908c69 nightly: pick up the Windows signing wrapper fix (#4846) 2026-11-27 09:53:58 -06:00
Dylan M. TaylorandFredApps 3bed16aea8 ci: notify artcraft-services on release state changes (#4832)
* ci: notify artcraft-services on release state changes

* ci: record notify-services workflow in actions.lock

The Lockfile check fails because the new workflow is not listed in actions.lock. It calls a reusable workflow and uses no action directly, so its entry is empty, like ci.yml.

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <[email protected]>
2026-11-27 09:18:02 -05:00
skylar taylor-barrick dd6a17d239 nightly: pin the signer timestamp fix (#4831)
Moves every nightly pin to craft-common-actions f94a4381 (the shared commit that reconciles a first signer attempt's creation time during historical verification as well as live admission). Exactly seven references across three files: both callers' uses and tooling-revision, and the policy's producer_tooling_revision, producer_workflow_ref and signer_tooling_revision. No other change.
2026-11-27 07:28:03 -06:00
FredApps 296a4bf9a6 Merge pull request #3341 from AnhNgoo/fix/filter-unicode-case-2912
AutoFilter: match Unicode case-insensitively (#2912)
2026-11-27 06:51:49 +01:00
FredApps 8cc5022abb fix(filter): match legacy checklist identities across merged case variants
Re-fold the stored base of every checklist identity with the Unicode case key
before comparing, so an identity saved with ASCII-only folding selects all rows
of the dropdown entry that now merges the case variants, and reapplying the
unchanged checklist keeps the same rows (#2912).
2026-11-27 12:39:41 +07:00
FredApps 4d5c8f2a4d fix(filter): keep ASCII-folded checklist identities matching their rows
Identities saved before the Unicode case key encode non-ASCII uppercase text
with ASCII-only folding. Accept that legacy base key when matching rows and
when deciding whether a selection splits formula and constant rows, so a saved
selection keeps its rows visible and its dropdown entry checked (#2912).
2026-11-27 12:26:59 +07:00
FredApps 1af87a37c5 Merge main into fix/filter-unicode-case-2912
Resolve the conflict with the checklist-identity matcher from #2943: apply the
char-wise Unicode lowercase key to the value-list lookup and to the typed and
formatted checklist identity tokens, so case variants share one dropdown entry
and match rows consistently. Update the two dropdown tests accordingly.
2026-11-27 12:12:32 +07:00
FredApps 401041f00c Merge pull request #3402 from AnhNgoo/fix/dialog-enter-error-2189
fix(ui): keep dialog errors visible after Enter (#2189)
2026-11-27 06:09:25 +01:00
FredApps 959497cad6 Merge pull request #2867 from AnhNgoo/fix/chart-explicit-style-rendering
fix(chart): render explicit Excel chart styles 1 and 9
2026-11-27 05:55:30 +01:00
FredApps c10f94fcd3 Merge pull request #2943 from AnhNgoo/fix/filter-whitespace-2911
fix(filter): ignore surrounding whitespace in AutoFilter values
2026-11-27 05:53:12 +01:00
AnhNgoo 5c4fcc65bd fix(filter): use char-wise lowercase keys matching compare_text 2026-11-27 10:39:51 +07:00
AnhNgoo 86a0c41e8f test(chart): use Series::default() for new upstream fields 2026-11-27 10:39:42 +07:00
AnhNgoo c159362b95 Merge remote-tracking branch 'upstream/main' into fix/filter-whitespace-2911
# Conflicts:
#	crates/engine/src/cmd/data.rs
#	crates/engine/src/cmd/data/filter.rs
#	crates/engine/src/cmd/data/tests.rs
#	crates/ui-egui/src/grid/menus.rs
2026-11-27 10:10:50 +07:00
AnhNgoo 93d8e97d16 Merge remote-tracking branch 'upstream/main' into fix/chart-explicit-style-rendering
# Conflicts:
#	crates/chart/src/resolve.rs
#	crates/xlsx/src/chart.rs
#	crates/xlsx/src/tests/chart_combo_kinds.rs
2026-11-27 10:10:44 +07:00
AnhNgoo 55d6879a94 Merge remote-tracking branch 'upstream/main' into fix/dialog-enter-error-2189
# Conflicts:
#	crates/ui-egui/src/dialogs/show.rs
#	crates/ui-egui/src/widgets.rs
2026-11-27 10:10:20 +07:00
AnhNgoo 791beee9f4 Merge remote-tracking branch 'upstream/main' into fix/filter-unicode-case-2912
# Conflicts:
#	crates/engine/src/cmd/data/filter.rs
2026-11-27 10:10:05 +07:00
alehelandClaude Opus 5.5 f45c122e79 Text defaults: the zero-sheet test saves and opens through GridCraft JSON
The test built its JSON with serde_json directly. It now saves with
io::save_bytes and opens with io::open_bytes, the craft-gridcraft-format
writer and reader main uses, empties the sheet list in between, and
gives the workbook a macro. One open then checks that the zero-sheet
reset carries both the text defaults and the macros. It fails when the
reset drops the text defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:01:22 +01:00
Claude 3c9fc0d7c2 Merge branch 'main' of https://github.com/storytold/gridcraft into ccr-64df7fff-37m0oz
# Conflicts:
#	docs/target-app-parity.md
2026-11-26 23:57:03 +00:00
alehelandClaude Opus 5.5 6868b7eb7b Merge storytold/gridcraft main into split/text-defaults
Main now reads GridCraft JSON through craft_gridcraft_format::read. That
reader deserialises the model with its own serde rules, so text_defaults
loads as before; the zero-sheet reset keeps carrying the macros and the
text defaults across.

Conflicts:
- crates/model/src/lib.rs: the re-export list takes both main's RefHost
  and WriteReservation and this branch's ScriptDefault and TextDefaults.
- docs/file-format-parity.md: main's header and history, with this
  branch's 2026-11-14 row placed among main's 2026-11-14 rows and its
  summary added to the header's "earlier" list in the same place.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:49:22 +01:00
Claude 39dacab93a #258: a formula typed next to a table's header row names the new column by its result
Auto-expansion named the new column before the edit was recalculated, so a
header formula such as =1+1 had no value yet and the column became Column1
(and the formula was overwritten with that name). The column is now named by
the formula's evaluated result, through the cell's number format, as Resize
Table names it, and the header keeps that result as constant text. Fixes the
two failing Resize Table tests in table_resize_overlap.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 23:47:53 +00:00
FredApps 5aa0bd29e2 Merge pull request #684 from neilcawse/fix/pivot-chart-series
XLSX: PivotCharts plot their cached points; deleted automatic titles stay off
2026-11-26 23:19:55 +01:00
FredApps 94cb40be98 Merge branch 'main' into fix/pivot-chart-series 2026-11-26 23:10:27 +01:00
FredApps ed881a564f Merge pull request #2270 from vedran-dobos/csv-sep-line
CSV: an Excel `sep=` first line names the delimiter (#1446)
2026-11-26 23:10:07 +01:00
FredApps 33e37398fd Merge branch 'main' into csv-sep-line 2026-11-26 22:57:27 +01:00
FredApps d88f56be7b Merge pull request #2556 from Silvertree2010/fix/2547-some-ascent-letters-displayed-fa
Set ő, ű and other Latin Extended-A letters in the Latin PDF font
2026-11-26 22:57:08 +01:00
FredApps 269eb10bed Merge branch 'main' into fix/2547-some-ascent-letters-displayed-fa 2026-11-26 22:46:35 +01:00
FredApps 90ec7db3b5 Merge pull request #722 from neilcawse/fix/pivot-refresh-fidelity
PivotTables: refresh keeps sort by value, captions, item order and layout settings
2026-11-26 22:46:19 +01:00
FredApps 7807aaed67 Merge main into the PivotChart cache branch 2026-11-26 22:44:18 +01:00
FredApps 565b4ea705 PDF: Latin Extended-A resources state /FirstChar, /LastChar, /Widths and a /FontDescriptor 2026-11-26 22:43:02 +01:00
skylar taylor-barrick 364e967e69 nightly: forward the thirteen signing secrets the sign steps actually read (#4802)
Merged under Skylar's Nightly 999: "let's do a final astra review and merge if it's good", after that Astra review returned no code blocker on this exact head, with CI, Sonar and CodeRabbit green on it and zero unresolved threads. No approval was added from Skylar's account.

Routine repin: seven literal pin substitutions across three files moving both callers and the policy from craft-common-actions 3dee1822 to 6bde9f8b. Fresh context check at merge time: head unchanged at 7a685125, mergeable CLEAN, and no .github or packaging drift between the base the hosted gate ran on (59f6b6c1) and main at 16c9ef0b.
2026-11-26 15:38:57 -06:00
FredApps b55ea8acd3 Merge branch 'main' into PR #2270
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 22:36:39 +01:00
FredApps 6fba6d3688 Merge branch 'main' into fix/pivot-refresh-fidelity 2026-11-26 22:32:36 +01:00
FredApps 16c9ef0b76 Merge pull request #2404 from helenkwok/charts/keep-unedited-chart-xml
XLSX: keep an unedited embedded chart's XML on save (#1668)
2026-11-26 22:32:05 +01:00
FredApps 989a267cb0 Merge branch 'main' into PR #259
# Conflicts:
#	docs/target-app-parity.md
2026-11-26 22:26:18 +01:00
FredApps 996c7ba467 Merge branch 'main' into charts/keep-unedited-chart-xml 2026-11-26 22:22:37 +01:00
FredApps 9e8fdbc2df Merge pull request #2227 from sonth87/i18n-vi
i18n: add Vietnamese (vi) interface translations
2026-11-26 22:22:20 +01:00
FredApps 088f9193a8 Merge branch 'main' into i18n-vi 2026-11-26 22:20:13 +01:00
FredApps 2f7ac98c44 Merge pull request #2651 from nihilist-narwhal/perf/xtask-bench
cargo xtask bench: calculation benchmarks on fixed in-code workbooks
2026-11-26 22:19:57 +01:00
FredApps 89bf004226 Merge branch 'main' into perf/xtask-bench 2026-11-26 22:06:30 +01:00
FredApps 59f6b6c14a Merge pull request #2331 from nihilist-narwhal/fix/no-merged-cells-in-tables
Tables never hold merged cells, which Excel removes the table for on open
2026-11-26 22:06:09 +01:00
FredApps 604cdf03f0 vi: translate the context-keyed Paste Special|Add and Text to Columns|Comma, as main's catalogs do 2026-11-26 22:04:37 +01:00
FredApps 279c530efd Merge main into the no-merged-cells-in-tables branch 2026-11-26 21:43:47 +01:00
FredApps abee6d6926 Merge branch 'main' into i18n-vi 2026-11-26 21:42:35 +01:00
FredApps 79285118ca Merge pull request #2645 from nihilist-narwhal/i18n/split-add-comma
i18n: Paste Special's Add and Text to Columns' Comma get their own keys
2026-11-26 21:42:11 +01:00
FredApps 072493baec Merge branch 'main' into i18n/split-add-comma 2026-11-26 21:29:29 +01:00
FredApps 707091be3f Merge pull request #2374 from Silvertree2010/fix/2230-hyperlink-function-does-not-work
Make HYPERLINK formula cells behave as clickable links
2026-11-26 21:29:05 +01:00
FredApps 3852c2335a Merge main into the Vietnamese catalog branch 2026-11-26 21:17:20 +01:00
FredApps 5bc7f92680 Merge branch 'main' into fix/2230-hyperlink-function-does-not-work 2026-11-26 21:16:21 +01:00
FredApps 04720627bd Merge main into the bench branch 2026-11-26 21:15:32 +01:00
FredApps 91f9b87070 Resize Table keeps main's refusal over merged cells (Excel's behaviour); test follows 2026-11-26 21:15:09 +01:00
FredApps 396c794844 Merge branch 'main' into fix/no-merged-cells-in-tables 2026-11-26 20:57:24 +01:00
FredApps 93e42af30d Merge pull request #2371 from marcoarnulfo/feat/print-selection
Print: Print Selection in File > Print > Settings, several selected areas print one after the other
2026-11-26 20:57:04 +01:00
FredApps cf9a1aba48 Merge branch 'main' into feat/print-selection 2026-11-26 20:43:26 +01:00
FredApps b5386047d9 Merge pull request #2656 from Harrison-Booth/gc-fix-text-cap
Cap text at 32,767 characters like Excel (#2635)
2026-11-26 20:42:50 +01:00
FredApps b8cd3891fb Merge branch 'main' into PR #2270
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 20:34:27 +01:00
FredApps 2469308bf6 Merge branch 'main' into PR #2404
# Conflicts:
#	ROADMAP.md
2026-11-26 20:34:18 +01:00
FredApps c5e735410a Merge branch 'main' into PR #2371
# Conflicts:
#	ROADMAP.md
2026-11-26 20:34:10 +01:00
FredApps 728f639332 Merge main into the PivotChart cache branch 2026-11-26 20:33:43 +01:00
FredApps 6f57f7f4ae Merge branch 'main' into gc-fix-text-cap 2026-11-26 20:30:10 +01:00
FredApps 6ec2bab62b Merge pull request #2508 from Harrison-Booth/gc-a24-password-to-modify
XLSX: password to modify is kept on save and asked for on open
2026-11-26 20:29:34 +01:00
FredApps eb73335d12 Merge branch 'main' into gc-a24-password-to-modify 2026-11-26 20:17:42 +01:00
FredApps 4b35af1609 Merge pull request #2602 from dotCooCoo/feat/chart-100-stacked-line
Charts: 100% Stacked Line, with or without markers, draws values as shares of each category's total
2026-11-26 20:17:22 +01:00
FredApps 2fbd3585af Merge branch 'main' into PR #2371
# Conflicts:
#	ROADMAP.md
2026-11-26 20:11:17 +01:00
FredApps e3f897ce7e Merge branch 'main' into PR #2508
# Conflicts:
#	ROADMAP.md
2026-11-26 20:11:00 +01:00
FredApps 2514c099b1 Merge branch 'main' into feat/chart-100-stacked-line 2026-11-26 20:06:17 +01:00
FredApps 34da5683a6 Merge pull request #2398 from Harrison-Booth/gc-irr-xirr-excel-solver
XIRR and IRR follow Excel's solvers
2026-11-26 20:05:40 +01:00
FredApps 24a0ce5a67 Merge main into the keep-chart-xml branch 2026-11-26 19:59:54 +01:00
FredApps a5039ec907 Merge main into the write-reservation branch 2026-11-26 19:58:21 +01:00
FredApps a09a6ac3c8 Merge branch 'main' into gc-irr-xirr-excel-solver 2026-11-26 19:52:13 +01:00
FredApps f70dcc0e2e Merge pull request #2506 from Harrison-Booth/gc-subtotal-filtered-rows-roundtrip
Filter: SUBTOTAL over filtered table rows keeps its value after save and reopen
2026-11-26 19:51:57 +01:00
FredApps c08f843218 Merge branch 'main' into PR #2270
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 19:45:43 +01:00
FredApps a99895c037 Merge branch 'main' into PR #2371
# Conflicts:
#	ROADMAP.md
2026-11-26 19:45:31 +01:00
FredApps 41b8ec1218 Merge branch 'main' into PR #2398
# Conflicts:
#	ROADMAP.md
2026-11-26 19:45:12 +01:00
FredApps 5fbc21b2b3 Merge branch 'main' into gc-subtotal-filtered-rows-roundtrip 2026-11-26 19:41:41 +01:00
FredApps f53f8ede73 Merge pull request #2499 from Harrison-Booth/gc-pivot-data-model-caches
XLSX: keep PivotTables on a data connection, the Data Model or another workbook on save
2026-11-26 19:41:21 +01:00
FredApps 55a9a23d04 Merge main into print-selection 2026-11-26 19:31:48 +01:00
FredApps dbc919b3f7 Merge branch 'main' into gc-pivot-data-model-caches 2026-11-26 19:31:03 +01:00
FredApps 916371a2b1 Drop newton and solve_rate: unused now that XIRR and IRR have their own solvers 2026-11-26 19:30:21 +01:00
FredApps e59e03cd9e Merge branch 'main' into gc-irr-xirr-excel-solver 2026-11-26 19:24:05 +01:00
FredApps eda1871f36 Merge pull request #2672 from TheRenegadeDev/fix/2641-cascading-autofilter-values
Fix cascading AutoFilter dropdown values
2026-11-26 19:23:43 +01:00
FredApps 74b93f3766 Merge branch 'main' into PR #2270
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 19:19:16 +01:00
FredApps 1dbd8db607 Merge branch 'main' into PR #2404
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 19:19:07 +01:00
FredApps 501fca9eb5 Merge branch 'main' into PR #2499
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 19:18:44 +01:00
FredApps 23d0784b11 Merge branch 'main' into fix/2641-cascading-autofilter-values 2026-11-26 19:10:55 +01:00
FredApps 6842aee683 Merge pull request #4139 from alehel/split/paper-table
model::paper: one paper-size table for print layout and XLSX (ODS groundwork)
2026-11-26 19:10:36 +01:00
FredApps 22b85c371f Merge branch 'main' into PR #2371
# Conflicts:
#	docs/ui-parity.md
2026-11-26 19:02:12 +01:00
FredApps 271ece082d Merge branch 'main' into PR #2672
# Conflicts:
#	docs/ui-parity.md
2026-11-26 19:01:51 +01:00
FredApps cc92d8a941 Merge branch 'main' into split/paper-table 2026-11-26 19:01:45 +01:00
FredApps c9b822b858 Merge pull request #2439 from DerKarussellbremser/synthetic-styles
Grid: italic and bold in a one-face font are slanted and thickened, as in Excel
2026-11-26 19:01:21 +01:00
FredApps ceaa6c129f Merge main into print-selection (resolve conflicts onto main's split print modules) 2026-11-26 18:55:44 +01:00
FredApps 7c5fec1a69 Merge branch 'main' into synthetic-styles 2026-11-26 18:51:33 +01:00
FredApps d5ebe99cd7 Merge branch 'main' into PR #2404
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 18:51:28 +01:00
FredApps 3dd804da3f Merge pull request #2650 from Harrison-Booth/gc-b09-excel-open-check
Excel open check: save workbooks with the CLI and open them in real Excel
2026-11-26 18:51:05 +01:00
FredApps dc5db3ccde Merge branch 'main' into PR #2270
# Conflicts:
#	docs/decisions.md
#	docs/file-format-parity.md
2026-11-26 18:50:55 +01:00
FredApps 8efbabf8e9 Merge branch 'main' into PR #2227
# Conflicts:
#	crates/ui-egui/src/i18n/vi.rs
2026-11-26 18:50:40 +01:00
FredApps f27f874e3c Merge branch 'main' into PR #2672
# Conflicts:
#	docs/ui-parity.md
2026-11-27 00:44:41 +07:00
FredApps b6dd901fe6 Merge branch 'main' into PR #2508
# Conflicts:
#	docs/file-format-parity.md
2026-11-27 00:44:18 +07:00
FredApps a2ac77711d Merge branch 'main' into PR #2499
# Conflicts:
#	docs/file-format-parity.md
2026-11-27 00:44:13 +07:00
FredApps d731fef146 Merge branch 'main' into PR #2439
# Conflicts:
#	docs/ui-parity.md
2026-11-27 00:44:08 +07:00
FredApps 77a569cf91 Merge branch 'main' into PR #2398
# Conflicts:
#	ROADMAP.md
2026-11-27 00:44:03 +07:00
FredApps 85d6d048d9 Merge branch 'main' into gc-b09-excel-open-check 2026-11-26 18:38:13 +01:00
FredApps c2ddc94c0d Merge pull request #2269 from vedran-dobos/autofit-test-real-font
AutoFit: a table's header is measured in the table style's bold font
2026-11-26 18:37:49 +01:00
FredApps 17e94d26d2 Merge branch 'main' into PR #2651
# Conflicts:
#	ROADMAP.md
2026-11-27 00:28:45 +07:00
FredApps 5c89c4adc2 Merge branch 'main' into PR #4139
# Conflicts:
#	docs/file-format-parity.md
2026-11-27 00:28:39 +07:00
FredApps 62c4cb3cb7 Merge branch 'main' into PR #2672
# Conflicts:
#	docs/ui-parity.md
2026-11-27 00:28:33 +07:00
FredApps 4744b591d1 Merge branch 'main' into PR #2650
# Conflicts:
#	ROADMAP.md
2026-11-27 00:28:27 +07:00
FredApps 0887efd788 Merge branch 'main' into PR #2439
# Conflicts:
#	docs/ui-parity.md
2026-11-27 00:28:21 +07:00
FredApps 2983959016 Merge branch 'main' into PR #2269
# Conflicts:
#	docs/ui-parity.md
2026-11-27 00:28:10 +07:00
FredApps 203b41a0c2 Merge pull request #1822 from alosslessdev/feat/color-scale-editor
Conditional formatting: 2-/3-colour scale editor with per-stop thresholds
2026-11-26 18:28:00 +01:00
FredApps 40dbdd23c6 Merge branch 'main' into feat/color-scale-editor 2026-11-26 18:16:51 +01:00
FredApps bd050fc833 Merge branch 'main' into PR #2499
# Conflicts:
#	ROADMAP.md
#	crates/xlsx/src/pivot/read.rs
#	crates/xlsx/src/pivot/write.rs
#	crates/xlsx/src/read.rs
#	crates/xlsx/src/write.rs
#	docs/file-format-parity.md
2026-11-27 00:16:08 +07:00
FredApps dbe301d9bb Merge pull request #2271 from vedran-dobos/format-widens-columns
Format: number formats widen columns that weren't sized by hand (#1077)
2026-11-26 18:16:08 +01:00
FredApps b22fa1d193 Resolve GridCraft paper-size integration conflicts 2026-11-26 18:13:07 +01:00
FredApps 35ea16aa63 Merge branch 'main' into PR #1822
# Conflicts:
#	contributors/people.toml
#	crates/engine/src/cmd/insert.rs
#	crates/ui-egui/src/dialogs/cond_format_rules.rs
#	crates/ui-egui/src/i18n/cs.rs
#	crates/ui-egui/src/i18n/de.rs
#	crates/ui-egui/src/i18n/el.rs
#	crates/ui-egui/src/i18n/es.rs
#	crates/ui-egui/src/i18n/fr.rs
#	crates/ui-egui/src/i18n/it.rs
#	crates/ui-egui/src/i18n/ja.rs
#	crates/ui-egui/src/i18n/ko.rs
#	crates/ui-egui/src/i18n/nl.rs
#	crates/ui-egui/src/i18n/pl.rs
#	crates/ui-egui/src/i18n/pt.rs
#	crates/ui-egui/src/i18n/ro.rs
#	crates/ui-egui/src/i18n/ru.rs
#	crates/ui-egui/src/i18n/sr.rs
#	crates/ui-egui/src/i18n/tr.rs
#	crates/ui-egui/src/i18n/uk.rs
#	crates/ui-egui/src/i18n/vi.rs
#	crates/ui-egui/src/i18n/zh.rs
2026-11-27 00:12:50 +07:00
FredApps 23fe90cd42 Merge branch 'main' into format-widens-columns 2026-11-26 18:04:12 +01:00
FredApps 545ed706a9 Merge pull request #2505 from Harrison-Booth/gc-table-resize-overlaps
Resize Table: refuse merged cells, PivotTables and arrays; name new columns like Excel
2026-11-26 18:03:24 +01:00
FredApps abda1fe767 Merge branch 'main' into gc-table-resize-overlaps 2026-11-26 17:49:50 +01:00
FredApps 508caac2d1 Merge pull request #2395 from Harrison-Booth/gc-f8-extend-add-selection
Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection
2026-11-26 17:48:45 +01:00
FredApps 313f50a96b Merge branch 'main' into PR #2508
# Conflicts:
#	ROADMAP.md
#	crates/model/src/lib.rs
#	crates/xlsx/src/write.rs
#	docs/file-format-parity.md
2026-11-26 23:48:42 +07:00
FredApps ac5bfaf3a6 Merge branch 'main' into PR #2506
# Conflicts:
#	crates/engine/tests/it/main.rs
#	crates/xlsx/src/sheet_write.rs
2026-11-26 23:44:02 +07:00
FredApps b38b2f8900 Merge branch 'main' into PR #2505
# Conflicts:
#	crates/engine/src/cmd/extra/data.rs
2026-11-26 23:40:42 +07:00
FredApps 3ac1f3746f Merge branch 'main' into PR #2398
# Conflicts:
#	ROADMAP.md
#	crates/functions/src/financial/tests.rs
#	docs/function-parity.md
2026-11-26 23:37:06 +07:00
FredApps 8c911f0f25 Merge branch 'main' into PR #2271
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-26 23:35:43 +07:00
FredApps 0d32f7a504 Merge branch 'main' into PR #2602
# Conflicts:
#	ROADMAP.md
2026-11-26 23:35:38 +07:00
FredApps aa2d0d1f17 Merge branch 'main' into PR #2395
# Conflicts:
#	ROADMAP.md
2026-11-26 23:35:24 +07:00
FredApps 09d25ecaf6 Merge pull request #2720 from Higgs32584/fix/print-image-copies-budget
Security: PDF export keeps a bounded amount of picture data across pages
2026-11-26 17:29:21 +01:00
FredApps 2c28d0fc7e Merge branch 'main' into PR #684
# Conflicts:
#	crates/xlsx/src/chart.rs
#	crates/xlsx/src/read.rs
2026-11-26 17:25:45 +01:00
FredApps 62aacb3e7e Merge branch 'main' into PR #722
# Conflicts:
#	crates/engine/src/pivot/items.rs
#	crates/xlsx/src/pivot/read.rs
2026-11-26 23:20:43 +07:00
FredApps 9120829df1 Merge branch 'main' into fix/print-image-copies-budget 2026-11-26 17:16:21 +01:00
FredApps 21df25dbed Merge pull request #2492 from Harrison-Booth/gc-extlst-passthrough
XLSX: keep self-contained workbook and sheet extLst entries on save
2026-11-26 17:14:40 +01:00
FredApps 167f25f405 Merge branch 'main' into PR #2270
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 23:10:03 +07:00
FredApps 8192019564 #258: the cells a growing row gives a calculated column are a set
grow_down checked every new cell against a Vec of filled cells, quadratic in
the table's width.
2026-11-26 23:09:10 +07:00
FredApps bfe8dd24f9 PDF: Latin Extended-A letters in an Arabic line's fallback runs use the extended font
A letter the Arabic face lacks (such as the Esperanto Ĉ) fell back to an
Item::Latin run in WinAnsi and printed as ?. Such runs are now Item::Ext, set
in the face's Latin Extended-A font, and the page declares that font.
2026-11-26 23:03:43 +07:00
FredApps ab445c1f7b Merge branch 'main' into gc-extlst-passthrough 2026-11-26 17:03:32 +01:00
FredApps 3352b90f1e Merge pull request #4377 from gmrmad1/contributors/gmrmad1
Contributors: add gmrmad1's name for the About window
2026-11-26 17:03:03 +01:00
FredApps e1b87cab01 Merge branch 'main' into PR #2556 2026-11-26 23:00:59 +07:00
FredApps 86a539e22b Merge branch 'main' into PR #2404
# Conflicts:
#	crates/xlsx/src/read.rs
#	crates/xlsx/src/sheet_write.rs
#	docs/chart-parity.md
#	docs/file-format-parity.md
2026-11-26 22:53:00 +07:00
FredApps b5766097e8 Merge branch 'main' into contributors/gmrmad1 2026-11-26 16:52:43 +01:00
FredApps 404c71b9c3 Merge pull request #2660 from Harrison-Booth/gc-fix-lambda
LAMBDA tail recursion reaches Excel's depth (5,459)
2026-11-26 16:52:27 +01:00
FredApps 8cee925a0b XLSX: a sheet without kept extensions skips the kept-extension scan on save
write_sheet_extensions called sheet_exts, which lowercases the extensions
just written, even when has_kept_exts was false (a preserved sheet with only
generated data bars or sparklines).
2026-11-26 16:49:51 +01:00
FredApps c1bc906ee7 Merge branch 'main' into PR #2492
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 16:49:51 +01:00
FredApps bc43e71e5b Merge branch 'main' into PR #2665
# Conflicts:
#	Cargo.lock
#	Cargo.toml
#	crates/xlsx/src/ods.rs
#	crates/xlsx/src/xlsb.rs
2026-11-26 22:45:28 +07:00
FredApps 7cff2527df Merge branch 'main' into gc-fix-lambda 2026-11-26 16:41:16 +01:00
FredApps b6ef428a89 Merge pull request #2628 from dotCooCoo/feat/fill-linear-growth-trend
Fill handle: Linear Trend and Growth Trend on the right-drag menu for numbers
2026-11-26 16:39:39 +01:00
FredApps 8f0ac5ad69 Merge branch 'main' into PR #2656
# Conflicts:
#	crates/calc/src/tests.rs
#	crates/chart/src/render/table.rs
#	crates/core/src/lib.rs
#	crates/core/src/value.rs
#	crates/functions/src/text.rs
#	crates/xlsx/src/tests/csv_tests.rs
2026-11-26 22:39:09 +07:00
skylar taylor-barrick 03fcfaa33b nightly: forward the signer's secrets from the caller, and allow just those (#4779)
Merged under Skylar's explicit Exec 476 grant after a fresh argon review returned MERGE on both halves, CI green on this head, and CodeRabbit on this head with no open threads.

Forwards exactly the fifteen signing secrets the shared nightly signer declares (craft-common-actions #376, pinned at 3dee1822), with no `environment:` anywhere, and relaxes one trust-closure assertion to exactly that allowlist for the signer caller only.
2026-11-26 09:30:39 -06:00
FredApps 4884d635a7 Merge branch 'main' into feat/fill-linear-growth-trend 2026-11-26 16:27:44 +01:00
FredApps ed4230f8b9 Merge pull request #2490 from Harrison-Booth/gc-fix-2335-table-spill
Calc: a one-value dynamic-array result in a table is not #SPILL!
2026-11-26 16:26:03 +01:00
FredApps 4a0d24013f Merge branch 'main' into gc-fix-2335-table-spill 2026-11-26 16:13:17 +01:00
FredApps 4ef9f58ecc Merge pull request #2302 from MarekSpodBiedry/issue-2213
Wayland: wheel without Ctrl scrolls again after a Ctrl+wheel zoom (#2213)
2026-11-26 16:12:12 +01:00
FredApps a79a50120c Merge branch 'main' into PR #2651
# Conflicts:
#	ROADMAP.md
2026-11-26 22:04:04 +07:00
FredApps 8de700ad93 Merge branch 'main' into issue-2213 2026-11-26 16:02:41 +01:00
FredApps cbefffe721 Merge pull request #2489 from Harrison-Booth/gc-array-entry-marks-all-cells
Recalc: array entry of a constant fills every cell and recalculates its readers
2026-11-26 16:01:45 +01:00
FredApps 2bb8f32254 Merge branch 'main' into PR #2227
# Conflicts:
#	crates/ui-egui/src/i18n/vi.rs
2026-11-26 22:01:06 +07:00
FredApps fa6c397a44 Merge branch 'main' into PR #2645
# Conflicts:
#	docs/localization-parity.md
2026-11-26 21:59:09 +07:00
FredApps def333fe42 #2230: HYPERLINK targets with a query, fragment or port open over https; a table name stays internal; a click resolves the link after committing an edit 2026-11-26 21:56:52 +07:00
FredApps d57bbabe76 Merge branch 'main' into PR #2374
# Conflicts:
#	crates/engine/src/tests.rs
2026-11-26 21:54:52 +07:00
FredApps c3ff583280 Merge branch 'main' into PR #2331
# Conflicts:
#	crates/engine/src/cmd/insert.rs
#	crates/engine/src/tests.rs
2026-11-26 21:53:15 +07:00
FredApps 4318d0e82e rustfmt the main merge under main's formatting config 2026-11-26 21:49:35 +07:00
FredApps 1c9a8ae835 Merge branch 'main' into gc-array-entry-marks-all-cells 2026-11-26 15:48:59 +01:00
FredApps 47a382c3e0 Merge branch 'main' into issue-2213 2026-11-26 15:41:16 +01:00
FredApps 3e888103c1 Merge pull request #4145 from alehel/split/password-forms
model, engine, xlsx: protection passwords keep both file forms; one shared base64 (ODS groundwork)
2026-11-26 15:40:24 +01:00
FredApps 0f36a7aee3 print tests: read the zip entry name through main's fallible ZipFile::name() 2026-11-26 21:34:27 +07:00
FredApps 1eff34e69d Merge branch 'main' into split/password-forms 2026-11-26 15:30:51 +01:00
FredApps 2d97c9c629 Merge branch 'main' into split/paper-table 2026-11-26 15:22:42 +01:00
FredApps 01be559f9d Merge pull request #2606 from zyzabruh/paste-transpose-refs
Paste Special: a transposed paste turns formula references as Excel does (fixes #2450)
2026-11-26 15:22:03 +01:00
FredApps 062c34b69a Merge branch 'main' into paste-transpose-refs 2026-11-26 15:11:43 +01:00
FredApps 2798b67d09 Merge pull request #2503 from Harrison-Booth/gc-sort-exact-number-order
SORT, SORTBY and Data > Sort order numbers exactly, like Excel
2026-11-26 15:11:17 +01:00
FredApps 7360e8c50b Merge branch 'main' into gc-sort-exact-number-order 2026-11-26 14:57:41 +01:00
FredApps 4870243e3f Merge pull request #2318 from marcoarnulfo/fix/zoom-not-undoable
View: zooming is not an undo step
2026-11-26 14:56:56 +01:00
FredApps 5f9b38946b #816: pdf: a later image budget never raises a lower one
set_image_budget says it lowers the budget, but a second call with more bytes raised it again (4 then 8 gave the next page 8 bytes). It now keeps the smaller of the two. Found by CodeRabbit.
2026-11-26 20:56:50 +07:00
FredApps 014e0583b7 Merge branch 'main' into PR #2395
# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/grid/keyboard.rs
#	docs/ui-parity.md
2026-11-26 20:56:02 +07:00
FredApps 8105980843 Merge branch 'main' into PR #2302
# Conflicts:
#	crates/ui-egui/src/grid/tests.rs
2026-11-26 20:44:58 +07:00
FredApps 0a785c7f12 Merge branch 'main' into fix/zoom-not-undoable 2026-11-26 14:44:08 +01:00
FredApps 60e424ee52 Merge pull request #2029 from kezmdor/fix/2023-plus-minus-starts-formula
Formula entry: a leading + or - starts a formula, like Excel (fixes #2023)
2026-11-26 14:43:48 +01:00
FredApps b876c97212 Merge branch 'main' into PR #2271
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-26 20:38:37 +07:00
FredApps 4e8562a9a4 Merge branch 'main' into PR #2029
# Conflicts:
#	docs/ui-parity.md
2026-11-26 20:34:00 +07:00
FredApps 66610a7a16 Merge branch 'main' into PR #2439
# Conflicts:
#	docs/ui-parity.md
2026-11-26 20:33:27 +07:00
FredApps 628b2c99f3 Merge branch 'main' into PR #2269
# Conflicts:
#	docs/ui-parity.md
2026-11-26 20:33:25 +07:00
FredApps e716c268ee Merge branch 'main' into fix/zoom-not-undoable 2026-11-26 14:32:39 +01:00
FredApps d4b8aae4d4 Merge pull request #2034 from kezmdor/fix/1834-autosum-edit-mode
AutoSum on one cell proposes its range in the editor, like Excel (fixes #1834)
2026-11-26 14:32:05 +01:00
FredApps 1e6c3f2a61 Merge branch 'main' into fix/1834-autosum-edit-mode 2026-11-26 14:22:35 +01:00
FredApps 168370bc2a Merge pull request #1393 from switch87/fix-1348-merged-selection-outline
Selection: a merged active cell is selected whole on open and on a sheet's first visit (#1348)
2026-11-26 14:22:11 +01:00
FredApps 9934dfd0b3 Merge branch 'main' into PR #2318
# Conflicts:
#	crates/engine/src/cmd/edit.rs
#	crates/engine/src/cmd/view.rs
#	crates/engine/tests/it/command_sequence_fuzz.rs
2026-11-26 20:22:04 +07:00
FredApps 37c5dbf021 Merge branch 'main' into PR #2492
# Conflicts:
#	crates/xlsx/src/read.rs
#	crates/xlsx/src/sheet_write.rs
#	docs/file-format-parity.md
2026-11-26 20:18:09 +07:00
FredApps 00bed75921 Merge branch 'main' into PR #2439
# Conflicts:
#	crates/ui-egui/src/grid/quadrant.rs
#	docs/ui-parity.md
2026-11-26 20:15:57 +07:00
FredApps 1b95f93b30 Merge branch 'main' into PR #2269
# Conflicts:
#	crates/engine/src/cmd/format.rs
#	docs/ui-parity.md
2026-11-26 20:06:10 +07:00
FredApps 6d12ac6720 Merge branch 'main' into fix-1348-merged-selection-outline 2026-11-26 14:06:10 +01:00
FredApps 7538c56868 Merge pull request #4603 from dotCooCoo/fix/zip-advisory
Deps: update zip past GHSA-m665-v7pm-7grj
2026-11-26 14:05:53 +01:00
FredApps bd943295a8 Merge branch 'main' into PR #2606 2026-11-26 20:04:25 +07:00
FredApps 4097668066 Merge branch 'main' into PR #4145
# Conflicts:
#	crates/engine/src/tests.rs
#	docs/file-format-parity.md
2026-11-26 19:59:48 +07:00
FredApps a53b23d470 Merge branch 'main' into PR #2503
# Conflicts:
#	crates/calc/src/tests.rs
#	crates/engine/src/tests.rs
2026-11-26 19:55:35 +07:00
FredApps 8466440421 Merge branch 'main' into fix/zip-advisory 2026-11-26 13:49:46 +01:00
FredApps 42abed0978 Merge branch 'main' into PR #2365
# Conflicts:
#	crates/engine/src/cmd/print/draw.rs
2026-11-26 19:44:26 +07:00
FredApps 531989a2e5 Merge branch 'main' into contributors/gmrmad1 2026-11-26 13:37:28 +01:00
FredApps fe30de8f7f Merge pull request #2636 from Zaxaerith/fix/2454-left-align-font-name
fix(ui): left-align the font name box (#2454)
2026-11-26 13:37:06 +01:00
FredApps 55222b8814 Merge branch 'main' into PR #1393
# Conflicts:
#	crates/engine/src/tests.rs
2026-11-26 19:36:28 +07:00
FredApps 3f8d3930bf Merge branch 'main' into fix/2454-left-align-font-name 2026-11-26 13:26:36 +01:00
FredApps fde057f8c2 Merge pull request #4257 from gmrmad1/fix/negative-fractional-basis-4058
fix(functions): reject a negative fractional basis instead of truncating it to zero (#4058)
2026-11-26 13:26:19 +01:00
FredApps 45181a217f Merge branch 'main' into PR #2650
# Conflicts:
#	ROADMAP.md
#	docs/gaps.md
2026-11-26 19:24:38 +07:00
FredApps 86a7d5e0c0 Merge branch 'main' into PR #2672
# Conflicts:
#	docs/ui-parity.md
2026-11-26 19:24:22 +07:00
FredApps 4d0333367b Merge branch 'main' into PR #4139
# Conflicts:
#	docs/architecture.md
#	docs/file-format-parity.md
2026-11-26 19:24:10 +07:00
FredApps 7436c503a9 Merge branch 'main' into PR #2034
# Conflicts:
#	docs/ui-parity.md
2026-11-26 19:23:52 +07:00
FredApps 5149a85932 Merge branch 'main' into PR #2029 2026-11-26 19:23:26 +07:00
FredApps c068f77254 Merge branch 'main' into fix/negative-fractional-basis-4058 2026-11-26 13:15:57 +01:00
FredApps 45ac58cf03 Merge branch 'main' into fix/2454-left-align-font-name 2026-11-26 13:15:26 +01:00
skylar taylor-barrick aab0a9c385 Nightly: open the Launcher's files rather than its --, and stop blocking a refused launch on macOS (#4775)
Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2). Folds in the review rounds: only options before `--` name the control channel (`-- --control` opens a document), documents keep command-line order across the separator, the launcher fixture takes the platform's absolute profile root, and the fixture is rustfmt-clean.
2026-11-26 05:30:10 -06:00
FredApps ccbf56c05c Merge pull request #4143 from alehel/split/cell-padding
Style model: cell padding kept in Alignment (groundwork for ODS)
2026-11-26 10:23:39 +01:00
FredApps a5709e22e0 Merge remote-tracking branch 'origin/main' into pr4143
# Conflicts:
#	docs/file-format-parity.md
2026-11-26 16:10:28 +07:00
FredApps 8fc8aa7857 Merge pull request #795 from vangel76/feat/quick-analysis-791
UI: Quick Analysis (Ctrl+Q) (#791)
2026-11-26 10:09:19 +01:00
FredApps aab64fdebc Merge pull request #4144 from alehel/split/font-outline
Fonts: outlined letters kept through XLSX open and save (groundwork for ODS)
2026-11-26 10:08:26 +01:00
FredApps 5fb3b44f69 Merge pull request #4166 from vangel76/fix/4162-nested-equation-colours
Nested equation colours stay per part after reopening a file
2026-11-26 10:07:56 +01:00
FredApps 9c7fc39563 Merge pull request #4267 from gmrmad1/fix/status-bar-stats-fit-4187
fix(ui): leave out status statistics that would overlap the mode text (#4187)
2026-11-26 10:07:24 +01:00
FredApps 6144228f45 Merge pull request #4699 from alehel/fix/cut-paste-keeps-cut-cells
paste: a cut moves only as a plain Paste onto one cell or its own size
2026-11-26 10:05:28 +01:00
skylar taylor-barrick de4e878aa8 Re-pin nightly callers to craft-common-actions 8389cad8 (signer Windows fix) (#4777)
Round-5 re-pin under Skylar's Nightly 891 signer-only roll (route A keeps the one-shared-pin invariant). Moves every nightly pin from craft-common-actions be00e5cc to 8389cad8, which carries the Windows ctime rule that stops the signer refusing a just-written JSON (#375). Only the pins and their docs move; no build or packaging code changes.
2026-11-26 00:41:08 -06:00
dotCooCoo dddc649a78 Merge main into fix/zip-advisory 2026-11-25 18:53:54 -08:00
skylar taylor-barrick b1216a17e8 Switch on supervised nightlies on the nightly-signer branch (#4767)
Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers.
2026-11-25 20:44:49 -06:00
aiongg 15373a0fe7 Merge pull request #4732 from aiongg/minimal-port-next
GridCraft: minimal port to craft-libs next
2026-11-25 19:07:46 -05:00
skylar taylor-barrick 3a37c2e882 Use the shared nightly launcher template (#4758)
Renders the plain nightly tar's launcher from craft-common-actions' shared template.

Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5.
2026-11-25 16:17:18 -06:00
aiongg f96096f97e The print job takes the panel's Collate; tests load their fonts as the app does 2026-11-25 20:44:58 +00:00
vangel76 731c90dcc1 Quick Analysis: use a focus ring colour that meets 3:1 on the popup in both themes
The sheet's green focus colour is only 2.5:1 on the dark popup (1.9:1 on a hovered tile).
Tiles now ring with the theme accent (3.9:1 or more on the popup, hover and pressed fills in
light and dark); the launcher sits on the sheet and keeps the sheet's focus colour. The
contrast test covers the popup pairs.
2026-11-25 20:52:50 +01:00
vangel76 8bbc760f5d Quick Analysis: name the launcher and tiles as buttons and show keyboard focus
The launcher and every tile now expose a button role with their translated label
(the launcher also its open state). The popup hands the keyboard to its first tile,
arrows move the focus between tiles, Enter or Space runs one, and the focused control
gets a visible ring. Ctrl+Q closes the popup while a tile has the keyboard.
2026-11-25 20:38:25 +01:00
vangel76 cfc0922126 Skip Office Math run styles when reading the legacy frame ink
The earlier writer saved a style-only m:rPr beside the a:rPr that carries the fill on styled runs. The legacy ink check counted it as a run without a fill and read Automatic.
2026-11-25 20:34:24 +01:00
aiongg 966c634b1c Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e 2026-11-25 19:15:01 +00:00
vangel76 e9449b55ab Read the frame ink of equations saved before the paragraph carried it
An older writer put the frame's ink on every Office Math run and wrote no fill on the paragraph end. With a colour command in the source, such an equation now reads that shared run colour instead of Automatic.
2026-11-25 19:09:50 +01:00
vangel76 7f2ae3cff8 Merge remote-tracking branch 'sm/main' into qa795
# Conflicts:
#	docs/ui-parity.md
2026-11-25 18:52:45 +01:00
vangel76 5682daedc1 Remove Quick Analysis translations from the GridCraft locale files
Keep English keys only; the translations move to a craft-i18n PR (AGENTS.md rule 16).
2026-11-25 18:52:35 +01:00
aiongg 3e43b2bce2 Repin craft-libs to storytold next aa401985d 2026-11-25 15:48:35 +00:00
aiongg 643b52cb29 Repin craft-libs to storytold next d1bdf8e5da 2026-11-25 13:43:38 +00:00
dotCooCoo c41535a75c Fill: rounding a filled number to 15 digits no longer allocates
round15 returns a whole number below 10^15 as it is and writes other
numbers to a stack buffer instead of a String, so a large fill does not
allocate for each cell. The results are the same bit for bit.
2026-11-24 23:29:26 -08:00
aiongg 4f7a511b9f Print page: widen the settings column so craft-print's Copies row does not wrap 2026-11-25 07:28:30 +00:00
dotCooCoo 1175b54e65 Fill: Linear Trend keeps the step of subnormal numbers
When every source number is smaller than 2^-600, the least-squares fit
runs on the numbers multiplied by 2^600 and scales its results back, so
the smallest doubles 1 and 2 times the minimum continue at 3 and 4 times
it instead of repeating.
2026-11-24 23:22:43 -08:00
aiongg acba6346ca Merge main into the minimal port
Conflicts: apps/gridcraft/src/main.rs (kept main's named App fields and nightly session code; kept the port's close_path, before_input and framework install/before_ui calls).
2026-11-25 06:35:12 +00:00
aiongg c2c9e2bc52 Repin egui to storytold b15ffe9bfc (what craft-libs next pins) 2026-11-25 06:32:47 +00:00
aiongg 73a2fd7148 Repin craft-libs to storytold next 16001e7210 and egui to storytold b15ffe9bfc 2026-11-25 06:31:18 +00:00
Dylan M. Taylor 33bb59307b packaging(linux): support co-installable nightly packages (#4733)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch.

Co-authored-by: Dylan M. Taylor <[email protected]>
2026-11-24 18:29:20 -06:00
aiongg 5c54cce8dc clippy: egui's ComboBox is the combo box on craft-libs next; Escape helpers take the context by value 2026-11-24 17:19:35 +00:00
aiongg 2f585b0edd Repin to craft-libs 3ad64a26ea: grid host-canvas registration back, semibold font mapping removed 2026-11-24 16:49:09 +00:00
aiongg 30fff82145 Clicks in tests wait for the release the runtime hands on a frame later; Escape leaves framework fields as GridCraft's own; runtime in the unit harnesses that draw the app 2026-11-24 16:35:05 +00:00
aiongg 786f88c0f6 Repin craft-libs to next-host-input 2f8d73e7cf; printers map through craft-print's From 2026-11-24 16:22:34 +00:00
aiongg b467062692 Grid keeps egui's focus without a host-canvas registration; close path in the macro editor harnesses; viewports native only 2026-11-24 16:12:27 +00:00
aiongg 2c4652d3d8 Host GridCraft's egui UI on craft-libs next's runtime
The runtime's four hooks in the desktop and web shells, the close path decided by
SheetApp::close_decision, Escape read through the window's cancel where no GridCraft
widget has the keyboard, the grid as the window's host canvas, the interface scale as
the runtime's RootEnv scale, fonts through craft_ui::fonts::load with the chrome's
families, the update dialogs on a DialogHost, and app-local copies of the removed
capture slot, combo menu and window viewports; the print controls on craft-print's ui
feature. Test harnesses that run the app install the runtime.
2026-11-24 15:52:54 +00:00
aiongg cf877fb11a minimal-port rewrite: 20 edits (combo 20) 2026-11-24 15:17:08 +00:00
aiongg c09881beaa minimal-port repin: 36 edits (revs 34, features 2) 2026-11-24 15:16:47 +00:00
dotCooCoo 5e2bca0ae7 Deps: raise the zip minimum to 9.8.2
The workspace requirement was 9.0.5 and the lockfile resolved zip 9.1.0.
Both now name 9.8.2, the current 9.x release, which includes the 9.2.3
follow-up fix for GHSA-m665-v7pm-7grj. The lockfile adds constant_time_eq
0.6.1, which zip 9.8.2 depends on.
2026-11-24 05:28:13 -08:00
dotCooCoo d23654cdf0 Merge main into feat/chart-100-stacked-line 2026-11-24 04:53:09 -08:00
alehel dd86b43150 paste: a cut is refused over any filter-hidden row it would land on, anchored or tall
The hidden-row check read the rows a tiled single-row paste skips, which is
empty for a paste at an explicit cell or a taller block, so those wrote into
hidden rows after the source was cleared. It now checks the cut's own
destination rows.
2026-11-24 04:38:18 +01:00
dotCooCoo f9b39debd2 Merge main into feat/fill-linear-growth-trend 2026-11-23 19:14:23 -08:00
NetterSilverandClaude Haiku 5.5 637e7809f0 Make HYPERLINK formula cells behave as clickable links
Fixes #2230

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-24 02:02:40 +01:00
alehel 7486d1021b paste: a cut moves only as a plain Paste onto one cell or its own size
One rule in one place replaces the Paste Link and filtered-row refusals.
A cut in this workbook empties its source before the destination is
written, so every paste that would not write each cut cell once, in one
place, loses or misplaces cells: a Paste Special option (link, skip
blanks, transpose, an operation, or pasting only part such as values),
tiling over a larger or differently shaped area, or rows a filter hides.
These are refused before anything changes, and the cut stays pending,
as in Excel. A single cell or an area of the cut's size takes it.

Tests: one per refused mode, each asserting nothing changed, plus a
refused paste followed by plain pastes that still move the cut.
2026-11-23 23:26:25 +01:00
alehel 35ca6435a8 paste: a cut is refused as Paste Link or into filtered-out rows before its source is cleared
Paste Link would write links to the cells the cut empties, and a
destination over rows the filter hides would skip cells the cut has
taken; both lost the cut cells.
2026-11-23 21:46:11 +01:00
alehel 8d6e207f04 xlsx: font outline goes through the shared craft-xlsx Font
The outline flag is read with craft_xlsx::Font::read and written with
craft_xlsx::Font::to_el, so its three states (absent, stated off, on)
follow the shared SpreadsheetML handling instead of a second reader and
writer here. The app keeps the mapping to Font::outline and
DxfStated::outline.
2026-11-23 13:59:05 +01:00
alehel 0d23a0b12c Merge storytold/gridcraft main into split/cell-padding
main added the issue #778 round-trip tests where this branch added its
cell-padding test; all three are kept.
2026-11-23 12:06:37 +01:00
alehel d4c97a3329 Protection passwords: GridCraft JSON stays readable by older versions
A password set in GridCraft is saved in the Iterated shape older
GridCraft versions read, with the SHA-256 digest in an extra `odf` field
they ignore, instead of a `Both` variant they reject (which made the
whole workbook fail to open). Reading the new shape gives both forms
back. Shapes older versions never had (a digest alone, or a digest with
a legacy hash) come only from OpenDocument files and keep their own.

Test: a_gridcraft_password_is_saved_so_older_versions_read_it reads a
new save with the pre-change PasswordHash definition.
2026-11-23 12:03:20 +01:00
alehel e16b5fa179 Merge storytold/gridcraft main into split/password-forms
Both sides added a test at the end of xlsx roundtrip.rs; both are kept.
2026-11-23 12:03:20 +01:00
alehel 7d0f153f9d json goldens: kept.json states "outline" too
kept.json is built from book.json, so it is re-blessed after it.
2026-11-23 11:58:53 +01:00
alehel d5c8c079cb Merge storytold/gridcraft main into split/font-outline
main moved the dxf writer into dxf_xml; the outline flags now go there.
main's new native JSON goldens are re-blessed: every font now states
"outline" (false when off), as this branch intends. Older readers ignore
the unknown key.
2026-11-23 11:58:27 +01:00
FredApps 30013b349c Reconcile status bar statistics with current main 2026-11-23 11:33:35 +01:00
alehel a1b96711b6 PR4139: verify imported ISO B5 print dimensions 2026-11-23 10:36:04 +01:00
dotCooCoo 2f4b702530 Charts: stacked and 100% stacked line groups on one axis open as a combo chart
The chart reader reports both groupings as stacked lines, so a chart holding both read every series as a 100% stacked line. Each series now takes its own group's kind, and the chart opens as a combo chart when those kinds differ.
2026-11-21 14:23:48 -08:00
dotCooCoo fdb96edf1f Merge main into feat/chart-100-stacked-line 2026-11-21 14:19:55 -08:00
Neil Cawse b8dcf17039 fix(xlsx): preserve explicit and automatic chart title semantics across craft-drawingml 2026-11-21 19:41:35 +00:00
Neil Cawse ed6ab029e8 fix(xlsx): rustfmt chart.rs and unpack read_chart tuple in trendline test 2026-11-21 19:10:30 +00:00
Neil Cawse 086a464792 Merge remote-tracking branch 'upstream/main' into fix/pivot-chart-series
# Conflicts:
#	crates/xlsx/src/chart.rs
2026-11-21 17:15:21 +00:00
Neil Cawse d8e5faee9b Merge remote-tracking branch 'upstream/main' into fix/pivot-refresh-fidelity 2026-11-21 17:07:49 +00:00
AnhNgoo 9d9c9cdf83 style: format slicer.rs according to rustfmt 2026-11-21 15:47:43 +07:00
AnhNgoo c00fb9b67e fix(slicer,filter): use Unicode lowercase for slicer deduplication and align formatted-value matching 2026-11-21 15:22:06 +07:00
AnhNgoo e86b2ef0ef fix(xlsx): remove duplicate closing braces in chart reader 2026-11-21 14:56:43 +07:00
AnhNgoo 1e087adf28 Merge branch 'main' of https://github.com/storytold/gridcraft into fix/chart-explicit-style-rendering 2026-11-21 14:36:50 +07:00
AnhNgoo 50a6ea444a Merge branch 'main' of https://github.com/storytold/gridcraft into fix/filter-whitespace-2911 2026-11-21 14:25:08 +07:00
AnhNgoo 7bd4c2d17b fix(filter): distinguish formatted displays in cell tokens and deduplicate slicer tiles 2026-11-21 14:25:02 +07:00
dotCooCoo 51ab33dbe3 CLI check: read package parts by entry index
The package checker listed entry names and then opened each part with
by_name. zip 9 decodes names not flagged UTF-8 as CP437, and by_name
cannot find such a name in its raw-name index, so every lookup scanned
and decoded all entries (up to MAX_ENTRIES). A name that does not
decode is listed lossy and by_name did not find it at all, and two
entries that decode to the same name were both read from the first.

zip_names now returns each entry's index with its name, and the
validator, the full-calc-on-load check and the relationship check read
parts with by_index. The relationship check caches verdicts per entry
index.
2026-11-20 18:56:11 -08:00
dotCooCoo dec0e1a6c0 Deps: update zip past GHSA-m665-v7pm-7grj
The workspace required zip 3, which resolved to zip 3.0.0 for
gridcraft-xlsx, gridcraft-cli and gridcraft-engine's tests. zip 3.0.0
is affected by GHSA-m665-v7pm-7grj (parser differential through dual
local and central headers; affected through 9.0.4, patched in 9.0.5).
The requirement is now 9.0.5, which resolves to the zip 9.1.0 that
craft-update and craft-zip already use, so one zip remains in the
lock file and arbitrary and derive_arbitrary drop out.

zip 9 returns entry names as a Result, decoding names not flagged
UTF-8 as CP437. The package checker in gridcraft-cli lists an entry
whose name does not decode under its raw bytes made lossy, so it is
still checked and reported. Tests unwrap the decoded names.
2026-11-20 17:33:46 -08:00
vangel76 c2a0cae3fe Reconcile Quick Analysis entries in the UI parity guide 2026-11-21 02:03:13 +01:00
vangel76 7f57431b57 Merge upstream/main into feat/quick-analysis-791 2026-11-21 02:01:53 +01:00
Vedran DobosandClaude Opus 5.5 06c16b3c8d Merge the branch's merges of main (FredApps, up to f8af138f) into format-widens-columns
This branch already has main 17e276f9, which contains f8af138f, and the same
changes; the tree stays as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 19:23:32 +01:00
Vedran DobosandClaude Opus 5.5 169f5660c3 Merge upstream main (17e276f9) into csv-sep-line
# Conflicts:
#	crates/engine/src/io.rs
#	docs/file-format-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 17:50:29 +01:00
Vedran DobosandClaude Opus 5.5 9e40767a60 Merge upstream main (17e276f9) into format-widens-columns
# Conflicts:
#	crates/xlsx/src/sheet_read.rs
#	crates/xlsx/src/sheet_write.rs
#	docs/file-format-parity.md
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 17:49:56 +01:00
Vedran DobosandClaude Opus 5.5 a730bbe78a Merge upstream main (17e276f9) into autofit-test-real-font
# Conflicts:
#	crates/ui-egui/tests/it/header_autofit.rs
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 17:49:13 +01:00
Vedran DobosandClaude Opus 5.5 bdf7d657a4 CSV: a sep= stand-in is never a character the file holds (#1446)
The stand-in delimiter for a sep= line that names none is now chosen once
over the whole body: a free noncharacter, else any free character. A text
that holds every character is refused instead of being split at U+FDD0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 17:48:14 +01:00
FredApps 3f3199fcbb Remove pivot reader import superseded by filter indexing 2026-11-20 09:41:17 +01:00
FredApps 427cfad27e Merge main into PivotTable refresh fidelity 2026-11-20 09:40:49 +01:00
FredApps 3c22a5fd7a Merge main into fix/pivot-chart-series 2026-11-20 09:34:05 +01:00
kezmdor 5236d8e4ba Merge remote-tracking branch 'upstream/main' into fix/1834-autosum-edit-mode
# Conflicts:
#	docs/ui-parity.md
2026-11-19 17:41:54 +01:00
kezmdor 5b59dbf73f Merge remote-tracking branch 'upstream/main' into fix/2023-plus-minus-starts-formula
# Conflicts:
#	docs/ui-parity.md
2026-11-19 17:41:36 +01:00
Higgs32584 9e1abd22a2 Merge branch 'main' of https://github.com/storytold/gridcraft into HEAD
# Conflicts:
#	crates/engine/src/cmd/print/objects.rs
2026-11-19 10:15:54 -05:00
AnhNgoo 0a642f86eb fix(filter): keep typed checklist identities across formats, Show Formulas, and XLSX 2026-11-19 15:14:46 +07:00
AnhNgoo 7e05f4e57e fix(chart): scan all AlternateContent style fallbacks and keep narrow-bar test below label cap 2026-11-19 14:10:57 +07:00
AnhNgoo 0329de4388 fix(filter): preserve checklist identities, formatted-blank values, and migrated visibility on open 2026-11-19 14:10:57 +07:00
vangel76 1da7c3ae92 Merge upstream/main into feat/quick-analysis-791 2026-11-18 18:38:43 +01:00
vangel76 cff2302172 Merge upstream/main into fix/4162-nested-equation-colours 2026-11-18 18:38:16 +01:00
FredApps 0ed3425179 Merge main into gc-fix-2335-table-spill
Signed-off-by: FredApps <[email protected]>
2026-11-18 21:54:21 +07:00
FredApps 81daff425b Merge main into format-widens-columns
Signed-off-by: FredApps <[email protected]>
2026-11-18 21:15:52 +07:00
FredApps 1cf5054de4 Merge main into fix/pivot-chart-series
Signed-off-by: FredApps <[email protected]>
2026-11-18 21:15:50 +07:00
FredApps ad45897ec5 Merge main into feat/chart-100-stacked-line
Signed-off-by: FredApps <[email protected]>
2026-11-18 21:15:48 +07:00
FredApps 93bb7443b2 Merge main into perf/xtask-bench
Signed-off-by: FredApps <[email protected]>
2026-11-18 21:15:47 +07:00
FredApps cb08a89917 Merge main into i18n-vi
Signed-off-by: FredApps <[email protected]>
2026-11-18 21:15:34 +07:00
FredApps 595a2ee0a8 vi: drop 13 entries that repeat keys translated earlier in the catalog
main added Sort-dialog, status-bar and Goal Seek strings to vi.rs after this
branch had translated them. The merge kept both copies, and clippy rejects the
later ones as unreachable match arms. The earlier entries are the ones in use,
so nothing shown changes.

Signed-off-by: FredApps <[email protected]>
2026-11-18 21:15:32 +07:00
FredApps f5737157a0 Merge main into feat/chart-100-stacked-line
Signed-off-by: FredApps <[email protected]>
2026-11-18 20:40:43 +07:00
FredApps 53fafbf5d5 Merge main into perf/xtask-bench
Signed-off-by: FredApps <[email protected]>
2026-11-18 20:40:43 +07:00
Higgs32584 f06ecfaceb #816: print test draws the cell picture through set_picture
The image-budget test inserted the cell picture into `cell_pictures` directly. The cell had no
value, so `draw_block` skipped it, and only the floating picture was measured. The test now uses
`Sheet::set_picture` and checks the cell picture's draws separately: one per page.
2026-11-18 08:24:06 -05:00
Higgs32584 0980f3aa2f Merge remote-tracking branch 'storytold/main' into fix/print-image-copies-budget
# Conflicts:
#	crates/engine/src/cmd/print/draw.rs
2026-11-18 08:24:06 -05:00
AlissonFAandClaude Opus 5.5 c77d94f07d #258: a growing table leaves the formulas already in its new cells to F9 in manual mode
Growth marked every cell of the new row or column as changed, so manual
mode evaluated a formula that was already there (B3 = E1*2 recalculated
when A3 grew A1:B2), though nobody edited it. Those cells now go to
Ctx::grown: automatic mode still recalculates their readers (ROWS,
COUNTBLANK, COLUMNS over the table), manual mode leaves them for F9. A
calculated column's formula the growth writes, and a header it names,
stay edits and are evaluated as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:18:08 -03:00
AlissonFAandClaude Opus 5.5 bc320680e1 Merge origin/main into feat/table-auto-expansion
Conflicts: the new Ctx fields from both sides are kept (rebuild_deps and
entry beside main's edits and recalc_all; refresh_equations runs before
the protection check), fill_dir and fill_series set cx.entry around
main's fill_except and SeriesOptions, tables.rs imports the union, and
the parity doc keeps both revision rows. Cells written by table growth
gain main's new `py` field. expand_pass is split into grow_down and
grow_right: main's cognitive-complexity limit refused it as one function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 10:14:47 -03:00
FredApps 06247bf36c Merge main into perf/xtask-bench
Signed-off-by: FredApps <[email protected]>
2026-11-18 19:51:52 +07:00
FredApps f8892ee1c1 Merge main into format-widens-columns
Signed-off-by: FredApps <[email protected]>
2026-11-18 19:51:51 +07:00
FredApps a87983891f Merge main into gc-irr-xirr-excel-solver
Signed-off-by: FredApps <[email protected]>
2026-11-18 19:51:49 +07:00
FredApps f7fd68e709 Merge main into i18n-vi
Signed-off-by: FredApps <[email protected]>
2026-11-18 19:51:48 +07:00
FredApps 7cf59c0a5a Merge main into feat/chart-100-stacked-line
Signed-off-by: FredApps <[email protected]>
2026-11-18 19:51:47 +07:00
FredApps 93378f27bb Merge main into fix/pivot-chart-series
Signed-off-by: FredApps <[email protected]>
2026-11-18 19:51:45 +07:00
FredApps b189d8f7df Merge main into gc-fix-2335-table-spill
Signed-off-by: FredApps <[email protected]>

# Conflicts:
#	crates/calc/src/recalc.rs
#	crates/calc/src/recalc/pass_host.rs
2026-11-18 18:55:20 +07:00
FredApps f187179552 Merge main into perf/xtask-bench
Signed-off-by: FredApps <[email protected]>

# Conflicts:
#	ROADMAP.md
#	docs/gaps.md
#	docs/target-app-parity.md
2026-11-18 18:49:22 +07:00
FredApps b92f45b004 Merge main into format-widens-columns
Signed-off-by: FredApps <[email protected]>

# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md
2026-11-18 18:49:22 +07:00
FredApps 46a8525585 Merge main into gc-irr-xirr-excel-solver
Signed-off-by: FredApps <[email protected]>

# Conflicts:
#	ROADMAP.md
#	docs/function-parity.md
2026-11-18 18:49:22 +07:00
FredApps ce12e9f7f8 Merge main into i18n-vi
Signed-off-by: FredApps <[email protected]>

# Conflicts:
#	docs/localization-parity.md
2026-11-18 18:47:39 +07:00
FredApps b75b155848 XLSX: the sheet-read test context sets the chart fields
`Ctx` gained `pivot_charts` and `chart_budget` on this branch, and the
test helper `ctx` that main added for #2159 did not set them.

Signed-off-by: FredApps <[email protected]>
2026-11-18 18:35:50 +07:00
FredApps 0a6e534676 Merge main into feat/chart-100-stacked-line
Signed-off-by: FredApps <[email protected]>
2026-11-18 18:35:31 +07:00
FredApps 0f2c32d1a8 XLSX: say the chart import budget is the workbook's, not one chart's
The point budget is shared by every chart in the workbook (`chart_budget` in
the read context), so the warning and the doc comment no longer call it per-chart.

Signed-off-by: FredApps <[email protected]>
2026-11-18 18:34:15 +07:00
FredApps d89a3afd22 Merge main into fix/pivot-chart-series
Signed-off-by: FredApps <[email protected]>
2026-11-18 18:34:10 +07:00
FredApps 36a932c933 Damaged-value warning: say a formula recalculates only for cells that have one
A constant cell's damaged value is dropped for good, so the warning no
longer claims a formula there calculates it again unless every dropped
cell has a formula; a mixed set says the cells with a formula do.

Signed-off-by: FredApps <[email protected]>
2026-11-18 17:24:23 +07:00
AnhNgoo 5e75ffe429 fix(ui): ignore key-repeat Enter/Escape events in message_box (#2189) 2026-11-18 16:55:30 +07:00
AnhNgoo 67bea056d5 fix(filter): migrate legacy whitespace criteria and separate dropdown labels from values (#2911) 2026-11-18 16:02:13 +07:00
AnhNgoo e6f5de7e42 fix(ui): drain modified Escape/Enter in message_box so open dialogs stay open (#2189) 2026-11-18 15:54:39 +07:00
AnhNgoo 14bc675778 fix(chart): preserve narrow style 9 bar fill and validate fallback style (#2865) 2026-11-18 15:47:28 +07:00
AnhNgoo e59c6dfda2 Merge upstream main and document chart style helpers (#2865) 2026-11-18 14:29:06 +07:00
AnhNgoo ef124ce4a9 Merge upstream main and preserve blank rows when filtering by whitespace value (#2911) 2026-11-18 14:18:05 +07:00
AnhNgoo e4d0388944 test(ui): cover dialog error recovery, OK click, and message priority (#2189) 2026-11-18 14:10:07 +07:00
dotCooCoo 384e6189e7 Merge main into feat/fill-linear-growth-trend 2026-11-17 21:26:23 -08:00
dotCooCoo 80897d8bd4 i18n: Linear Trend and Growth Trend have a row in every catalog
The right-drag fill menu shows both labels through lang.tr, and no catalog had a row for them, so every interface language showed them in English. Each of the 18 catalogs now translates them, and a test checks that none falls back to English.
2026-11-17 20:25:52 -08:00
Neil Cawse 7299661159 Merge remote-tracking branch 'upstream/main' into fix/pivot-refresh-fidelity 2026-11-18 04:18:49 +00:00
Neil Cawse dea77f4811 Merge remote-tracking branch 'upstream/main' into fix/pivot-chart-series 2026-11-18 04:18:46 +00:00
Higgs32584 187f88aa1c #816: pdf: refused pictures past the image budget add no duplicate-index entry
Page::image_rgba looked up same-page duplicates with image_index.entry(..).or_default(),
which inserted an empty entry before a picture past the budget was refused. Distinct
same-size pictures could then grow the index without bound. The lookup is now
non-inserting, and an entry is added only for an accepted picture. The comment about
the temporary lookup copy now says it is bounded by pixel dimensions the page already
accepted, not by the bytes of a kept image.
2026-11-17 22:39:52 -05:00
dotCooCoo 6429399f20 Fill: the trend menu walks lanes and checks signs with the fill's helpers
trends_that_apply, numeric_lanes and Pattern::growth now share lane_cells and
growth_sign, so the right-drag menu and edit.autoFill use one lane walk and one
Growth Trend sign rule.
2026-11-17 18:07:14 -08:00
MarekSpodBiedry 69a36a3b37 Print: skip hidden rows and columns when measuring overflowing text, as draw_block does (#2333) 2026-11-18 00:47:44 +01:00
MarekSpodBiedry 33eaca4524 Merge remote-tracking branch 'origin/main' into review-2365 2026-11-18 00:46:57 +01:00
Neil Cawse fe730ad3fc fix(engine): use Ctx and FieldItems in fill_line_values item_refs 2026-11-17 13:30:48 +00:00
Neil Cawse e435c58930 Merge remote-tracking branch 'upstream/main' into fix/pivot-chart-series 2026-11-17 13:25:17 +00:00
Neil Cawse 710ece507c Merge remote-tracking branch 'upstream/main' into fix/pivot-refresh-fidelity 2026-11-17 13:24:47 +00:00
NetterSilverandClaude Opus 5.5 43bf785515 Set ő, ű and other Latin Extended-A letters in the Latin PDF font
Fixes #2547

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-17 08:04:05 +00:00
Madhav Agarwal d977856457 ci: run rustfmt over the status bar statistics test 2026-11-17 12:42:22 +05:30
Neil Cawse a05d381c5c Merge remote-tracking branch 'upstream/main' into fix/pivot-refresh-fidelity
# Conflicts:
#	crates/engine/src/pivot/compute.rs
#	crates/model/src/features.rs
#	crates/xlsx/src/tests/pivot_tests.rs
#	docs/target-app-parity.md
2026-11-17 04:21:41 +00:00
Neil Cawse e7177f4948 Merge remote-tracking branch 'upstream/main' into fix/pivot-chart-series
# Conflicts:
#	crates/engine/src/cmd/insert.rs
2026-11-17 04:20:33 +00:00
vangel76 c395f2d60b Merge upstream/main into feat/quick-analysis-791 2026-11-16 21:53:15 +01:00
Madhav Agarwal fc4701104c Contributors: gmrmad1's name for the About window 2026-11-16 20:05:50 +05:30
Madhav Agarwal 2537e5ff0a review: count egui's item spacing in the status statistics fitting budget (CodeRabbit)
The status bar reserves 10 points after each statistic with add_space, and egui
adds item_spacing.x after every label as well (6 points in the theme). Passing
only 10 to fitting_statistics could keep a sixth statistic that then painted
over the mode text. Pass the sum, and sweep the widths where the sixth label
only just fits.
2026-11-16 20:04:57 +05:30
Higgs32584 ba59c101c4 Merge remote-tracking branch 'storytold/main' into fix/print-image-copies-budget
# Conflicts:
#	crates/engine/src/cmd/print.rs
#	crates/engine/src/cmd/print/draw.rs
#	crates/engine/src/cmd/print/objects.rs
2026-11-16 09:29:18 -05:00
dotCooCoo 3d38b86232 Merge main into feat/chart-100-stacked-line 2026-11-15 13:51:59 -08:00
dotCooCoo 4091ad6fe7 Merge main into feat/fill-linear-growth-trend 2026-11-15 13:51:28 -08:00
alehel 5f73d9787c Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:18 +01:00
alehel 7d571db2d0 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:18 +01:00
alehel 7c3b4e288a Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:18 +01:00
alehel dd1ba0e33d Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:17 +01:00
alehel 4d5ff9dc6a Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:17 +01:00
dotCooCoo 3f6de52269 Merge main into feat/chart-100-stacked-line 2026-11-15 09:05:51 -08:00
Vedran DobosandClaude Opus 5.5 a7ae5a8668 CSV: the sep= line counts against the output limit (#1446)
A save that puts a sep= line first checks the limit with the line included,
so a file at the cap is refused instead of growing past it. The CSV row in
file-format-parity.md now says when a sep= line is written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 16:14:13 +01:00
Vedran DobosandClaude Opus 5.5 111fc70b75 XLS: COLINFO's fUserSet marks a column width set by hand (#1077)
Main now reads .xls with the shared craft-xls crate, which reports fUserSet
but not fBestFit. A test covers fUserSet, no flags, and both flags; the docs
say what the .xls reader can tell apart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 16:13:06 +01:00
Vedran DobosandClaude Opus 5.5 cf6e4a57a8 Merge upstream main (8bde636f) into autofit-test-real-font
# Conflicts:
#	crates/engine/src/cmd/format/sizes.rs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:40:21 +01:00
Vedran DobosandClaude Opus 5.5 7853f14449 Merge upstream main (8bde636f) into csv-sep-line
# Conflicts:
#	crates/xlsx/src/csv.rs
#	crates/xlsx/src/tests/csv_tests.rs
#	docs/file-format-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:28:54 +01:00
Vedran DobosandClaude Opus 5.5 f678a3f99c Merge upstream main (8bde636f) into format-widens-columns
# Conflicts:
#	crates/xlsx/src/xls.rs
#	docs/file-format-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:22:25 +01:00
Vedran DobosandClaude Opus 5.5 3316bac277 CSV: a save that would reopen with another delimiter names its own (#1446)
Saving drops quotes a field no longer needs, so `"a,b";x` read with `;` was written `a,b;x`, a tie
that detection gives to comma, and `a;b;c|d;e;f` saved with commas read back as `;`. The `sep=`
line the first-row guard already writes now also goes first whenever detection on the written
text would pick another delimiter. Test: csv_save_names_its_delimiter_when_reopening_would_pick_another
(fails without the fix). decisions.md no longer promises more than this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 14:16:13 +01:00
vangel76andClaude Sonnet 5.5 fe07dbc654 Treat an equation as GridCraft's own only while its marker matches
When another application rewrote the Office Math, the source is rebuilt
from it and the saved paragraph-end ink no longer applies: the first
run's colour is the frame ink.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-15 13:54:06 +01:00
vangel76andClaude Opus 5.5 8b9f9527f1 Read GridCraft's saved equation ink only from its own Office Math
The paragraph-end ink and the colour-command rule apply to GridCraft's own
Office Math only: another writer's paragraph-end formatting is not the
frame's ink, and the plain-text box of an equation outside the Office Math
subset carries the ink on its runs. Adds the external-file, text-only and
combined nested-colour save/reopen tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-15 13:29:06 +01:00
Madhav Agarwal 7769efdbb9 functions: reject a negative fractional basis instead of truncating it to zero (#4058) 2026-11-15 15:15:13 +05:30
Madhav Agarwal c46a90c8c8 ui: leave out status statistics that would overlap the mode text (#4187) 2026-11-15 15:07:26 +05:30
Zaxaerith 2ae710e65b Merge upstream main and keep font name alignment (#2454) 2026-11-15 16:17:50 +08:00
nihilist-narwhal f32fefddcf Tables never hold merged cells, which Excel removes the table for on open
A table with a merged cell in it opened in Excel with the repair prompt, and Excel removed the
table and its AutoFilter ("Removed Feature: Table from /xl/tables/table1.xml"). GridCraft let
merged cells into a table four ways; each now does what Excel does:

- Merge Cells, Merge & Center and Merge Across refuse a range that touches a table ("You can't
  merge cells in a table."). Unmerging is still allowed, so a file that has one can be fixed.
- Insert Table / Format as Table and Resize Table unmerge the merged cells the table covers
  (observed: Excel creates the table and A2:B2 is no longer merged).
- Paste brings merged areas along, except into a table, where the cells arrive unmerged.

The command-sequence fuzzer checks the invariant (it found the paste case, seed 230).
2026-11-14 19:43:09 -06:00
David ArdilaandClaude Opus 5.5 35996c6e2e M-perf: bench: the egui 0.37 plan's Recalc scene points at cargo xtask bench, not the removed perf example
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:45 -06:00
nihilist-narwhalandClaude Opus 5.5 d56e3638fd M-perf: bench: recalc.full recalculates a stale result; malformed --rows/--reps is an error
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:45 -06:00
nihilist-narwhalandClaude Opus 5.5 f17f730887 M-perf: bench: median of an even count averages the middle two
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:45 -06:00
nihilist-narwhalandClaude Opus 5.5 a4aee78391 M-perf: bench: Scenario type alias (clippy type_complexity)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:45 -06:00
nihilist-narwhalandClaude Opus 5.5 815627264f bench: address review (empty filter, row-count-exact checks, fresh formula entry)
- A --filter that selects no scenario is an error, so --save can't
  write an empty baseline.
- edit.sumifs and edit.lookup derive their expected values from the
  rows actually generated, so any --rows passes.
- edit.lookup edits the key of a checked lookup (XLOOKUP falls back to 0
  when it is gone), so a lookup that stops recalculating fails the check.
- enter.formulas clears B1:Bn untimed before each run, so it times entry
  into empty cells, not an overwrite of the previous run's formulas.
- xtask: a relative CARGO_TARGET_DIR resolves against the workspace
  root, as cargo does for the bench; an existing baseline that doesn't
  parse is an error instead of "no baseline".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:45 -06:00
nihilist-narwhalandClaude Opus 5.5 b98a7c43de cargo xtask bench: calculation benchmarks on fixed in-code workbooks
Ten scenarios (crates/engine/examples/bench.rs, replacing the ad-hoc perf
example) build their workbooks in code, warm up, and time edits, formula
entry, Calculate Now, sort and XLSX save/open through Session::execute,
checking each result so a scenario that stops recalculating fails instead
of getting fast. A failed scenario is reported and the rest still run.
`cargo xtask bench` runs them in release, writes <target>/bench/latest.json
and compares with a baseline saved by --save.

Baseline (M2 Pro, 100k rows): a 100k-dependent edit recalculates in
90-106 ms; 100 whole-column SUMIFS take ~0.5 s per edit. xlsx.open fails
on main: the #2413 element cap drops the last ~9,000 rows of the 100k-row
model on reopen (fixed by #2527). Parity docs, gaps and roadmap carry the
measured numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:45 -06:00
nihilist-narwhalandClaude Opus 5.5 ad7ec8d775 i18n: the key-split test lets a catalog translate the two uses differently
The test required `Paste Special|Add` and `Text to Columns|Comma` to show
the same text as the plain keys, which forbids the very split it guards
(Spanish: Sumar vs Agregar). It now checks that a catalog translating the
plain label also translates the keyed one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:30 -06:00
nihilist-narwhalandClaude Opus 5.5 28086016fe i18n: Paste Special's Add and Text to Columns' Comma get their own keys
"Add" is both a Paste Special operation and the Solver's Add button, and
"Comma" both the Text to Columns delimiter and the Comma cell style. One
translation can't fit both (Spanish Excel: Sumar vs Agregar, Coma vs
Millares), and open PRs are about to translate the Solver button and the
cell-style gallery. The two dialog options now use `Paste Special|Add` and
`Text to Columns|Comma`; English shows the same labels and every catalog
carries its current translation onto the new key, so nothing visible
changes. A test checks both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 19:42:30 -06:00
Gert Pellin 8aa01a7750 Selection: a merged active cell is selected whole on open and on a sheet's first visit (#1348)
A click goes through selection.set, which takes merged cells whole, but the
selection a workbook opens with (built from the sheet's saved active cell)
and the default A1 a sheet starts at on its first visit were bare cells. With
A1:AG1 merged, opening the file outlined A1 alone.

Both now expand merges before the selection is shown. A sheet's remembered
selection is left as it was, so only the first visit is expanded.
2026-11-15 01:50:53 +01:00
dotCooCoo 512bf992f5 Fill handle: Growth Trend repeats the same number exactly
A lane that holds one number repeated went through the logarithm and
back, so two cells of 1e300 filled 9.99999999999976e299. Such a lane is
now copied unchanged, as a lone number already was.
2026-11-14 13:03:18 -08:00
dotCooCoo 322cc7e93a Fill handle: huge numbers keep every digit in Linear Trend and Fill Series
Rounding to 15 significant digits divided by an inexact power of ten,
so a number near the largest double came back with a changed 16th
digit: three copies of the largest double filled 1.797693134862311e308.
The rounding now goes through the number's exact decimal expansion, and
a number whose rounding would pass the largest double keeps its value.
2026-11-14 12:57:38 -08:00
Neil Cawse 045f938332 Merge remote-tracking branch 'upstream/main' into fix/pivot-refresh-fidelity
# Conflicts:
#	crates/xlsx/src/tests/pivot_tests.rs
2026-11-14 18:06:33 +00:00
Neil Cawse 61a3a47940 Merge remote-tracking branch 'upstream/main' into fix/pivot-chart-series 2026-11-14 18:04:58 +00:00
vangel76andClaude Sonnet 5.5 7cd04cd023 Keep the frame colour of an equation apart from its coloured runs in xlsx
An equation saved with colour commands has coloured runs; reading the file took
the first run's colour as the frame's ink, so the parts the source leaves
uncoloured turned that colour and the whole equation was painted in one colour.
The writer now saves the ink on the paragraph, and the reader of GridCraft's own
equations reads it from there.

Fixes #4162

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-14 13:01:06 +01:00
alehel 810b95bf68 Text defaults: a JSON workbook without sheets keeps them on open
When GridCraft JSON has no sheets, the reader replaces the workbook with
Workbook::new() and carries only the macros across, so its text defaults
were dropped and a save lost them. They are carried across too.
2026-11-14 10:54:29 +01:00
alehel 8cb34cd312 model::paper: say what an empty paper means today; every table paper keeps an XLSX id
Review round 1.
- PrintSettings::paper and the docs said an empty paper is "a file that stated none", but no
  reader produces it yet. They now say empty means no paper is stated, which a reader may set.
- for_size documents that it names the page as it stands (17x11 in is Ledger), so a caller that
  also records landscape passes the size upright.
- xlsx: a test that every paper in model::paper::PAPERS saves with an id and reads back as
  itself, so the two tables cannot drift. B6 (ISO) is the one exception (ECMA-376 has no
  upright ISO B6 id).
2026-11-14 08:52:38 +01:00
alehel a85ee924d6 Merge storytold/gridcraft main into split/text-defaults 2026-11-14 08:29:50 +01:00
alehel 0d868b83df Text defaults: keep ODF's script code and BCP 47 language tag
ODF 1.2 states a default language with fo:script and style:rfc-language-tag
(and their -asian/-complex forms) as well as fo:language/fo:country. Without
them, locales such as sr-Latn-RS or ca-ES-valencia would lose their script or
variant on an ODS round trip, and adding them later would be a breaking model
change. ScriptDefault gains `script` and `rfc_language_tag`, both skipped in
JSON when unset and counted by is_empty. The `font` doc now says it holds the
family name (not a style:font-face name) and that western.font is unused; the
"no language" note says zxx is the language and none the country.

The test round-trips sr-Latn-RS and fails if is_empty ignores either new field.
2026-11-14 08:29:24 +01:00
alehel 05b883379a Text defaults: field doc says empty until a reader fills them 2026-11-14 08:29:24 +01:00
alehel ba6385b388 Text defaults: revision row in the history table; doc says no reader fills them yet 2026-11-14 08:29:24 +01:00
alehel 989782f1a0 Model: workbook text defaults (languages, Asian/complex fonts)
Adds ScriptDefault { language, country, font } and TextDefaults
{ western, asian, complex } with is_empty, and Workbook::text_defaults,
exported from the model crate. An OpenDocument file states these on its
default cell style; Excel has no equivalent, so XLSX ignores them. The
field is kept in GridCraft JSON and skipped when empty, so a workbook
without it serialises exactly as before.
2026-11-14 08:29:24 +01:00
alehel 292a0e1e8e Merge storytold/main into split/font-outline
main moved the .xls BIFF reader to craft-xls (storytold/craft-libs), deleting
crates/xlsx/src/xls/styles.rs. The round-1 .xls fOutline read is dropped with
it, and the .xls style test and docs row go back to main's: craft-xls's Font has
no outline flag yet, so reading it belongs in craft-libs.
2026-11-14 02:20:20 +01:00
alehel 60ec576e0c Fonts: outline test comments and docs dates brought up to date
Review round 2 found no defects; this rewords the dxf fixture's doc comment
(one dxf also states strike), folds the .xls fixture's outline flag into its
description, and dates the docs row and timestamp line to the round-1 fixes.
2026-11-14 02:03:38 +01:00
alehel c0feebc9b4 Merge remote-tracking branch 'origin/main' into split/password-forms
# Conflicts:
#	crates/engine/src/tests.rs
#	crates/xlsx/src/crypto.rs
#	crates/xlsx/src/testing.rs
#	docs/file-format-parity.md
2026-11-14 01:54:51 +01:00
alehel cb42d58c54 model: cite ODF's protection-key sections and the digest-algorithm attribute
Review round 2 of the password-forms change: table:protection-key is ODF 1.3 part 3
section 19.701, not 19.699. The Sha256Digest doc now also says the form needs
table:protection-key-digest-algorithm (19.702) naming SHA-256, so an ODS writer writes
both attributes and a reader does not store a key under another algorithm as this form.
Workbook.structure_password says a digest alone is not written to XLSX, as the sheet
field does.
2026-11-14 01:54:13 +01:00
alehel 04c30b4901 Merge storytold/gridcraft main into split/cell-padding
Alignment gained reading_order on main; padding sits after it. The .xls reader moved to craft-xls, so its mapping in crates/xlsx/src/xls.rs sets no padding instead of the removed xls/styles.rs. file-format-parity.md keeps both histories.
2026-11-14 01:54:03 +01:00
alehel 349fb760b1 Fonts: outline cleared through Format Cells, read from .xls, dxf gate tested
Review round 1 on outlined letters:
- Font::outline is now always serialized. The Format Cells dialog sends the
  active cell's whole style to the selection through home.formatCells, which
  merges JSON; with the field skipped when false, a plain active cell never
  cleared outline on the other selected cells, while bold and the rest were
  overwritten. Older JSON without the field still opens.
- The legacy .xls reader reads the Font record's fOutline flag (0x0010), so an
  outlined .xls font no longer opens solid and is lost on save as .xlsx.
- dxf_outline_font_survives_save gains a dxf whose only font part is
  <outline val="0"/>, the case the write gate's st.outline term exists for.
2026-11-14 01:51:24 +01:00
alehel 7e8ffc7474 model, engine: test the workbook password's digest; correct protection docs; table base64 lookup
Review round 1 of the password-forms change.
- engine: passwords_set_in_gridcraft_survive_xlsx_saving now asserts that Protect Workbook
  also keeps the SHA-256 digest. Before, reverting protect_workbook to SHA-512 only passed
  every test.
- model: the password module doc says only sheet and workbook passwords keep both forms
  (edit ranges keep Excel's); SheetProtection.password and Workbook.structure_password no
  longer say they are always written to XLSX.
- model: b64 decodes each character through a match instead of scanning the alphabet, as
  xlsx/crypto.rs did before it moved to the shared decoder; a test checks the lookup is the
  alphabet's inverse for every byte.
2026-11-14 01:46:15 +01:00
alehel 21306e150f Style model: test that padding alone writes no <alignment>
Review fix-up. Reverting `alignment_xml` to compare the whole Alignment
left every test passing: an empty `<alignment/>` with `applyAlignment`
reads back as the default, so comparing styles could not see it. The
round-trip test now reads `xl/styles.xml` and checks that only the fully
aligned style writes `<alignment>` and `applyAlignment`.
2026-11-14 01:21:42 +01:00
alehel 82397d57ac Merge remote-tracking branch 'origin/main' into split/paper-table
# Conflicts:
#	docs/architecture.md
#	docs/file-format-parity.md
2026-11-13 21:47:23 +01:00
Neil Cawse cd4ea7b481 Merge remote-tracking branch 'upstream/main' into fix/pivot-chart-series
# Conflicts:
#	crates/xlsx/src/read.rs
2026-11-13 19:36:36 +00:00
Neil Cawse ff4d018290 Merge remote-tracking branch 'upstream/main' into fix/pivot-refresh-fidelity
# Conflicts:
#	crates/engine/src/pivot.rs
#	crates/engine/src/pivot/compute.rs
#	crates/engine/src/pivot/output.rs
2026-11-13 19:28:11 +00:00
Higgs32584 edc9afad59 pdf: draw a picture the page already holds after the image budget is spent
Look up a same-page duplicate before refusing a picture for lack of budget room.
Past the budget, the lookup copy is built only when the page holds an image of the
same pixel size, so it is never bigger than one already kept.

The engine budget test now counts image bytes once per page that references them,
since the writer shares identical images across pages.
2026-11-13 11:23:36 -05:00
Higgs32584 c4d0aa8773 Merge storytold/main into fix/print-image-copies-budget
# Conflicts:
#	crates/pdf/src/lib.rs
2026-11-13 11:09:20 -05:00
dotCooCoo 6d02203e8f Fill handle: the menu leaves out trends for fills AutoFill refuses
fill::trends_that_apply answers for Linear Trend and Growth Trend from
one read of the source, checking each cell's number and sign without
fitting a line or curve, and the right-drag menu calls it once instead
of calling trend_applies for each trend. Both return false, without
reading any source cell, when the source or target holds more than
MAX_FILL_CELLS cells or the target does not hold the source in a
corner, the same checks edit.autoFill applies.

New engine tests fill a two-column source down and a two-row source
across with each trend and check every value, and check that undo after
a Linear Trend fill restores the targets and leaves the source as it was.
2026-11-12 14:33:41 -08:00
vangel76andClaude Sonnet 5.5 7ee5c5ef36 Quick Analysis: refuse sparklines on a protected sheet
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 20:48:07 +01:00
vangel76andClaude Sonnet 5.5 d70646adfc Merge upstream/main
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 20:46:37 +01:00
Higgs32584 46dc11dc9f Merge storytold/main into fix/print-image-copies-budget
# Conflicts:
#	crates/engine/src/cmd/print.rs
#	crates/engine/src/cmd/print/objects.rs
2026-11-12 08:14:32 -05:00
alosslessdev e2174a9595 dax: rename computed-flag test to what it checks (#2228)
The fresh review notes isafter_evaluates_a_computed_flag_once cannot
observe evaluation count: constant IF flags return the same Boolean on
a second evaluation, so the assertions pin direction only. Rename to
isafter_accepts_a_computed_order_flag and say so in the comment; the
single-evaluation guarantee is structural (flag_direction takes no
evaluator to re-evaluate with).
2026-11-12 06:33:31 -05:00
alosslessdev 50e660c119 dax: evaluate each ISAFTER/ISONORAFTER Order flag once (#2228)
compare_groups evaluated a computed Order flag twice: is_order_flag
during the pair split, then order_flag_value for the direction. A
volatile flag (RAND () > 0.5) could change direction between the two
reads. Cache the evaluated Scalar per candidate; the split test and
the direction read both use it.

Test: isafter_evaluates_a_computed_flag_once pins IF-computed TRUE
and FALSE flags for ISAFTER and ISONORAFTER.
2026-11-12 06:20:09 -05:00
Helen Kwok 94fbd67d78 XLSX: keep an unedited embedded chart's XML on save (#1668)
On read, each embedded chart GridCraft models keeps its chart part and
the style, colour and user-shape parts behind it in Sheet.preserved,
with the chart as read. On save, the original part is written in place
of the generated one while the model chart still equals what was read
(id and position aside) and every sheet its formulas name still exists;
otherwise, and on any kept-content failure, the chart is written from
the model as before. Chartex charts are not kept.
2026-11-12 18:26:10 +08:00
TheRenegadeDev cea63e0611 2641: merge main and preserve imported filter row bounds
Keep main's imported-range clamp when combining row filtering with the
shared matcher, and carry that bound into statistics and dropdown choices.
Retain the duplicate-color and per-window pending-state corrections.

Add a last-row regression for Top 1 and Above Average, without trimming
the stored workbook. Main's version, dependencies and CI stay unchanged.
2026-11-11 15:27:15 -06:00
vangel76andClaude Sonnet 5.5 ca5796662f Merge upstream/main
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 21:54:21 +01:00
alehel ba605b4f69 Fonts: a differential format's outline turned off survives save
A dxf with <outline val="0"/> read as unset and was saved without it, unlike
bold, italic and strike, which keep their stated-off form. DxfStated gains
`outline` (serde default, so older JSON opens), read in read_dxf and written
by font_xml as <outline val="0"/>.
2026-11-11 10:32:38 +00:00
alehel bb91ea0410 model: bound decoded Iterated hash and salt; document the JSON form and the unwarned XLSX loss
Review follow-up: the Iterated form's hash and salt from a file are decoded
with decode_limited (1 KiB cap). The parity doc says a digest-only password is
saved to XLSX without a warning (the save path has no warning channel) and that
GridCraft JSON now holds such passwords as `Both`, which older versions can't read.
2026-11-11 10:31:22 +00:00
alehel f21dc313db model::paper: nearest-size match, new papers documented and tested
- for_size picks the nearest paper within 2 mm (as it stands, else
  turned) instead of the first in table order: Letter and Japanese
  Envelope Kaku #3 are less than 4 mm apart.
- Page Setup and Size list Statement, Envelope #10 and Envelope DL in
  their params docs; a test checks both commands store and print them.
- Paper docs are format-neutral.
2026-11-11 10:28:45 +00:00
alehel fd664055df Fonts: outlined letters kept through XLSX open and save
An XLSX font's <outline/> was never read, so outlined (hollow) letters came
back solid after a save. The model's Font gains `outline` (serde default
false, left out of JSON when off, part of the hand-written Hash), read in
read_font and written by font_xml after <strike/> as Excel orders it, for
cell fonts and differential formats. home.formatCells sets it through the
style JSON. GridCraft does not draw outlined text yet.

Split out of the ODS branch, which also maps style:text-outline onto it.
2026-11-11 09:19:20 +00:00
alehel 72778aba99 model, engine, xlsx: protection passwords keep both file forms; one shared base64
A sheet or workbook protection password set in GridCraft is now kept as
PasswordHash::Both: Excel's salted SHA-512 hash and the unsalted SHA-256
digest OpenDocument stores (PasswordHash::Sha256Digest). Unprotecting
verifies it; XLSX writes the form it can store, and a digest alone keeps its
protection without the password. Edit ranges keep only the SHA-512 form.

The public gridcraft_model::b64 (with a bounded decode_limited) replaces the
private base64 copies in engine io.rs, xlsx crypto.rs and xlsx testing.rs.
2026-11-11 09:04:34 +00:00
alehel 2a506bfc85 model::paper: one paper-size table for print layout and XLSX
Paper names and sizes now live in one table, `gridcraft_model::paper`
(`canonical`, `size_pt`, `for_size`). The engine's `known_paper` and the
XLSX writer's alias list read it instead of keeping their own copies.

- Page Setup and `pageLayout.size` store a known paper under its table
  name (`11x17` -> `Tabloid`, `b5-jis` -> `B5`), so every file format
  finds it.
- XLSX paper id 34 (ECMA-376 "B5 envelope, 176 x 250 mm", the ISO B5
  size) reads as `B5 (ISO)`; `B5 (ISO)` now saves with paperSize 34
  instead of none. `Envelope B5` is still accepted as an alias.
- Statement, Envelope #10 and Envelope DL print on their own size.
- `PrintSettings::paper` documents an empty name as "the file stated no
  paper": layout falls back to Letter and XLSX writes no paperSize. New
  sheets still default to Letter.
2026-11-11 09:04:00 +00:00
alehel 09d52cc7cd Style model: cell padding kept in Alignment
`Alignment::padding: [Option<u16>; 4]` (left, right, top, bottom, in
hundredths of a point; `None` where a file states none) holds an
OpenDocument cell's padding, which LibreOffice lays rows out with. It is
part of style equality and hashing, so styles that differ only by padding
intern apart; serde default, skipped when all `None`, so older JSON reads.

Excel has no cell padding: the XLSX and XLS readers set none, and the
XLSX writer leaves it out (a style that differs from the default only by
padding writes no `<alignment>`). GridCraft does not draw padding yet.
2026-11-11 09:02:08 +00:00
Vedran DobosandClaude Opus 5.5 313fdef652 Merge upstream main (a36e4987) into csv-sep-line
# Conflicts:
#	docs/file-format-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:18:43 +01:00
Vedran DobosandClaude Opus 5.5 92b3ab1886 Merge upstream main (a36e4987) into format-widens-columns
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:18:42 +01:00
Vedran DobosandClaude Opus 5.5 84e0a241b7 Merge upstream main (a36e4987) into autofit-test-real-font
# Conflicts:
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:18:41 +01:00
vangel76andClaude Sonnet 5.5 6315dacc9e Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 22:01:44 +01:00
dotCooCoo 0afc01aa1a Merge main into feat/chart-100-stacked-line 2026-11-10 10:28:18 -08:00
kezmdor 57de9d5d6f Merge upstream main into fix/1834-autosum-edit-mode
docs/ui-parity.md keeps main's rows with this change added.
2026-11-10 17:39:16 +01:00
kezmdor f56753ddb7 Merge upstream main into fix/2023-plus-minus-starts-formula
docs/ui-parity.md keeps main's rows with this change added.
2026-11-10 17:39:10 +01:00
TheRenegadeDev 19b8009d2a 2641: preserve filter choices across colors and window actions
Keep a duplicate value checked when any eligible row matches the current
criterion. Stop processing outgoing popup state when a form button switches
the active window during grid interaction.

Add regressions for fill/font color duplicates, other-column exclusion,
unchanged Apply, and a real button press preserving another window's search
and checkbox edits.
2026-11-10 08:04:37 -06:00
TheRenegadeDev 618ad0ba74 Merge main into cascading AutoFilter values (#2641)
Preserve main's Arabic filter ordering and sheet geometry/format caches
alongside cascading eligibility, criterion-based checkbox state and
per-window pending popup edits. Keep upstream dependency and CI choices.

Resolve the parity document's summary and history insertions by retaining
main's updated wording and all three AutoFilter history entries.
2026-11-10 06:20:21 -06:00
nihilist-narwhalandClaude Opus 5.5 5f5dda7249 JSON workbooks: loaded ranges are ordered and on the sheet, damaged arrays are dropped (#2160)
`RangeRef` and `Array` were deserialized as written. A range with its corners swapped wrapped
`height()`/`width()` (about 4.29e9 in release, which then drove loops; a panic in debug, outside
`Session::execute` once it reached render or recalc), and an array shorter than rows × cols was
indexed past its end.

Like Excel with a damaged file, the open goes on and the damage is repaired:

- `RangeRef` loads through `RangeRef::new` with both corners clamped to the grid, so every range
  in a file (merges, tables, rules, print areas, charts…) is fixed in one place, and a file that
  was valid loads unchanged.
- `Value::is_well_formed` checks every array in a value, nested ones too, without recursion.
  Opening a JSON workbook drops a cell value that fails it before anything reads the cells, with
  a warning naming the cell; opening recalculates, so a formula there gets its value back.
  Python results already go through `enforce_python_limits`, whose check now uses it, so a
  damaged array nested in a result of the right shape is dropped too. The only stored values a
  JSON workbook holds are cell values and Python results (spills and parsed formulas aren't
  saved).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 23:17:21 -06:00
dotCooCoo ed1f3964af Merge main into feat/fill-linear-growth-trend 2026-11-09 08:03:58 -08:00
dotCooCoo ad380da0e9 Merge main into feat/chart-100-stacked-line 2026-11-09 07:27:37 -08:00
dotCooCoo 094ce5ec8d Merge main into feat/chart-100-stacked-line 2026-11-09 00:01:34 -08:00
Neil Cawse 1b128ffb24 test(engine): add missing Chart fields in pivot chart test 2026-11-09 01:45:43 +00:00
Neil Cawse 1fb2dfd720 Merge origin/main into fix/pivot-chart-series 2026-11-09 01:20:29 +00:00
Neil Cawse d5cdd4b335 Merge origin/main into fix/pivot-refresh-fidelity 2026-11-09 01:13:23 +00:00
alosslessdev 23d2906408 Merge upstream/main into feat/color-scale-editor (#1822)
The about dialog takes main's 820 width; newFormattingRule stays in the 520 list.
2026-11-08 10:10:43 -05:00
vangel76andClaude Opus 5.5 d098a7dfc3 UI: Excel for Mac Control+Q opens Quick Analysis; Command+Q stays Quit
ribbon::shortcut is only reached with the command modifier, so on a Mac
Control+Q did nothing and Command+Q toggled Quick Analysis next to the
native Quit item. The keymap now maps Mac Control+Q (without Command,
Option or Shift) to Shortcut::QuickAnalysis, which shares the ribbon
handler and its single-cell alert suppression, and the ribbon Q branch
ignores Command on a Mac.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 12:41:12 +01:00
vangel76 7984f0f2bd Merge upstream/main into feat/quick-analysis-791 2026-11-08 12:37:22 +01:00
vangel76andClaude Sonnet 5.5 302019d815 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 18:39:42 +01:00
vangel76andClaude Sonnet 5.5 2240950eb6 Quick Analysis: Esc closes the popup only; bind it to the sheet's identity
Esc used to clear the pending copy and Format Painter before the popup saw it.
The popup also remembers the sheet by its identity rather than its position,
so moving sheets cannot hand it to another sheet.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 17:39:33 +01:00
vangel76andClaude Sonnet 5.5 a7a319c5c7 Quick Analysis: close the popup when the active sheet changes
The popup remembered only the range, so another sheet with the same selection
kept it open and the tiles ran against that sheet. It now remembers the sheet
too.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 17:26:11 +01:00
Harrison Booth 30f24fd239 Pass series index to chart table lookup 2026-11-07 10:05:00 -06:00
Harrison Booth fe9162c9cf Merge remote-tracking branch 'upstream/main' into gc-fix-text-cap 2026-11-07 10:02:51 -06:00
Harrison Booth ee886d6db6 Merge remote-tracking branch 'upstream/main' into gc-irr-xirr-excel-solver
# Conflicts:
#	ROADMAP.md
2026-11-07 08:49:56 -06:00
kezmdor 2829120d4d Recently Used: a sign before a space starts a formula too
main's `functions_in_formula` test expected `- SUM(1)` not to be a formula.
With #2023's rule, which `is_formula_input` now uses, it is one, as Excel
for the web enters `- remember this` as `=- remember this`.
2026-11-07 14:24:10 +01:00
kezmdor def4067247 AutoSum: main's Function Library test expects the proposal in the editor
Formulas › AutoSum and its Count Numbers item on one cell now leave
`=SUM(A1:A3)` / `=COUNT(B1:B3)` in the editor until Enter, as in Excel
(#1834); the test checks the proposal, presses Enter, then the cell.
2026-11-07 14:22:50 +01:00
kezmdor 51bc57b489 Merge upstream main into fix/1834-autosum-edit-mode
docs/ui-parity.md keeps main's rows with this change added.
2026-11-07 14:09:37 +01:00
kezmdor 0622859f49 Merge upstream main into fix/2023-plus-minus-starts-formula
main's new `is_formula_input` now asks `starts_formula`, so cell entry and
Formulas > Recently Used read a leading sign the same way; the Python
formula check stays first. docs/ui-parity.md keeps main's rows with this
change added.
2026-11-07 14:09:22 +01:00
Harrison Booth 3b70b106ef Merge remote-tracking branch 'upstream/main' into gc-extlst-passthrough
# Conflicts:
#	crates/xlsx/src/read.rs
2026-11-06 04:03:25 -06:00
alosslessdev c7e254c372 dax: split ISAFTER/ISONORAFTER pairs before consuming order flags (#2228) 2026-11-05 19:44:19 -05:00
alosslessdev 38e98cbe9b dax: aggregation, logical, information and model-info functions (#2228) 2026-11-05 19:09:28 -05:00
alosslessdev 98d7238838 dax: document the flat-chain depth limit and clear the wrong sugar links (#2228) 2026-11-05 18:53:23 -05:00
alosslessdev 77c6bfb286 Merge remote-tracking branch 'upstream/main' into coreL3406 2026-11-05 18:11:24 -05:00
alosslessdev 9fab68fd8f dax: list exponentiation as left-associative in the operator table (#2228) 2026-11-05 17:55:08 -05:00
Harrison Booth c8ef1b8b1b Merge remote-tracking branch 'upstream/main' into gc-sort-exact-number-order
# Conflicts:
#	ROADMAP.md
#	crates/calc/src/tests.rs
2026-11-05 15:39:09 -06:00
Harrison Booth 9291c39687 Merge remote-tracking branch 'upstream/main' into gc-pivot-data-model-caches
# Conflicts:
#	ROADMAP.md
2026-11-05 15:38:27 -06:00
Harrison Booth 8b0949f8ae Merge remote-tracking branch 'upstream/main' into gc-irr-xirr-excel-solver
# Conflicts:
#	ROADMAP.md
2026-11-05 15:37:29 -06:00
Harrison Booth 5f0e1d1347 Merge remote-tracking branch 'upstream/main' into gc-f8-extend-add-selection
# Conflicts:
#	ROADMAP.md
2026-11-05 15:37:00 -06:00
Vedran DobosandClaude Opus 5.5 62899818be Model: restore the ellipsis in LineInfo::custom's doc comment
Garbled into three characters when it moved to features/print.rs in the merge of main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:55:16 +01:00
alosslessdev f9921b99c8 dax: blank a repeated Outline label under folded equality (#2228) 2026-11-05 15:48:36 -05:00
Vedran DobosandClaude Opus 5.5 f90c2c0fe2 CSV: a .tsv save writes no sep= line (#1446)
The guard that puts a sep= line before a first row reading like one is for CSV, which is read
by detection. A .tsv or .txt file is read with tabs given, so the line came back as an extra
row and moved every row down (CodeRabbit). write_tsv writes without it; Save as .tsv uses it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:47:48 +01:00
Vedran DobosandClaude Opus 5.5 de3d3073e0 Merge upstream main (c4029538) into csv-sep-line
# Conflicts:
#	docs/file-format-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:39:46 +01:00
Vedran DobosandClaude Opus 5.5 f33a2eb90a Merge upstream main (c4029538) into format-widens-columns
# Conflicts:
#	docs/file-format-parity.md
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:39:45 +01:00
Vedran DobosandClaude Opus 5.5 7fc0147965 Merge upstream main (c4029538) into autofit-test-real-font
# Conflicts:
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:39:44 +01:00
alosslessdev ccb757dff2 dax: align the storage and functions-reference docs with the typed aggregates (#2228) 2026-11-05 15:32:30 -05:00
alosslessdev 2464b4f6aa dax: intersect filters and narrow pivot cells under folded equality (#2228) 2026-11-05 15:30:02 -05:00
alosslessdev 0ade51f7aa dax: keep filter keys in their own variant and fold at comparison (#2228) 2026-11-05 14:54:44 -05:00
alosslessdev 94bdc71889 dax: fold numeric variants in filter and distinct keys, and guard non-finite serials (#2228) 2026-11-05 14:40:14 -05:00
alosslessdev 8662072a92 Merge remote-tracking branch 'upstream/main' into coreL3406 2026-11-05 13:50:14 -05:00
alosslessdev 1198e1ddf9 dax: state the valid WEEKNUM codes and name the real pivot remedy (#2228) 2026-11-05 13:36:13 -05:00
alosslessdev a8b9913c31 dax: give CONTAINSROW evaluable documented examples (#2228) 2026-11-05 13:20:41 -05:00
alosslessdev 682d777b85 dax: count nonblank dimension NaN keys in the integrity report (#2228) 2026-11-05 12:49:18 -05:00
alosslessdev 0f074e4702 dax: note that Excel agrees on left-associative exponentiation (#2228) 2026-11-05 12:33:44 -05:00
alosslessdev 6f965710c0 dax: keep non-finite finding keys JSON-safe and count NaN foreign keys (#2228) 2026-11-05 12:20:47 -05:00
alosslessdev 581b085e9b dax: make exponentiation left-associative like every DAX operator (#2228) 2026-11-05 12:14:28 -05:00
alosslessdev 68389e865b dax: report NaN foreign keys as orphans and name the supported ALL functions (#2228) 2026-11-05 12:03:46 -05:00
alosslessdev c040089f8d dax: clear NAMEOF's volatile flag, infer Pow as Decimal and widen the scope note (#2228) 2026-11-05 11:36:02 -05:00
alosslessdev 10a2c02378 dax: exclude NaN keys from joins and apply the currency rule to strict equality (#2228) 2026-11-05 10:23:35 -05:00
alosslessdev 39ece863d8 dax: keep NaN and inexact currency keys out of the normalized join (#2228) 2026-11-05 10:05:43 -05:00
Harrison Booth 5d578bef00 Record model SHA-1 dependency in lockfile 2026-11-05 09:05:11 -06:00
Harrison Booth c3969a34c9 Merge upstream main into modify password PR 2026-11-05 08:44:13 -06:00
alosslessdev b3e25437cc dax: normalize numeric keys in propagation, integrity and hop lookups (#2228) 2026-11-05 09:39:45 -05:00
alosslessdev 88717cd5ac dax: compare integers exactly across variants and keep DATATABLE types keywords (#2228) 2026-11-05 09:35:46 -05:00
Harrison Booth 8fbd9ea4ab Merge upstream changes into PivotTable preservation 2026-11-05 08:28:53 -06:00
alosslessdev b4c8238594 dax: count every non-blank value in the implicit Count measure (#2228) 2026-11-05 09:28:18 -05:00
Harrison Booth c3c7ac378d Merge upstream changes into XLSX extension preservation 2026-11-05 08:20:42 -06:00
Harrison Booth 1ec173a087 Merge upstream changes into XIRR solver 2026-11-05 08:18:20 -06:00
Harrison Booth d16e311b8c Merge upstream changes into selection modes 2026-11-05 08:17:08 -06:00
alosslessdev 707cbc0742 dax: compare same-variant integers exactly (#2228) 2026-11-05 09:07:37 -05:00
alosslessdev a8e8bd70c6 dax: normalize numeric relationship joins, scope keyword shadowing and tidy the pivot docs (#2228) 2026-11-05 08:22:37 -05:00
alosslessdev d24debac57 dax: give families a per-evaluation memo slot and state the CUSTOMDATA limit (#2228) 2026-11-05 07:44:04 -05:00
alosslessdev 2af770def2 dax: document IN at the comparison tier (#2228) 2026-11-05 07:25:57 -05:00
alosslessdev 14916f64af dax: drop the unused manifest dependency and align the pivot filter doc (#2228) 2026-11-05 07:22:07 -05:00
alosslessdev f00e1da135 dax: document the variable index and look through VAR/RETURN in operand checks (#2228) 2026-11-05 07:20:13 -05:00
alosslessdev c37fa6a799 dax: read the browser clock for NOW/TODAY on wasm (#2228) 2026-11-05 06:59:49 -05:00
alosslessdev 292f0a3447 dax: bind every repeated order pair of SAMPLE and TOPNSKIP (#2228) 2026-11-05 06:36:15 -05:00
alosslessdev 5e1b519955 dax: carry the grouping scope, read integer columns exactly and put IN in the comparison tier (#2228) 2026-11-05 05:43:43 -05:00
alosslessdev 278f95e26a dax: replay the umbrella's hop index, blank-key orphan rule and CONCATENATEX pairs (#2228) 2026-11-05 05:28:35 -05:00
alosslessdev 6dbb9e3c8e dax: take the pivot, integrity and functions-reference files into the core slice (#2228) 2026-11-05 04:59:09 -05:00
alosslessdev 9e7497210b dax: let a large numeric key match itself in strict equality (#2228) 2026-11-05 04:54:21 -05:00
alosslessdev e96107dae5 dax: keep exact whole inputs, folded groups and exact relationship keys (#2228) 2026-11-05 04:34:47 -05:00
alosslessdev 934561c3ae dax: make the README example compile as Rust and drop the CLI sentence (#2228) 2026-11-05 04:23:16 -05:00
alosslessdev 3f5c55a052 dax: join numeric keys by value in strict equality (#2228) 2026-11-05 04:17:30 -05:00
alosslessdev d1cc151fc7 dax: bind the documented ASC/DESC slots of RANK.EQ, TOPNSKIP, SAMPLE and CONCATENATEX (#2228) 2026-11-05 03:47:57 -05:00
alosslessdev 21212be16a Merge remote-tracking branch 'upstream/main' into coreL3406 2026-11-05 03:47:40 -05:00
alosslessdev 5a73c66a1f dax: fold text in filter matching and harden keywords, months and pivot docs (#2228) 2026-11-05 03:41:58 -05:00
alosslessdev 7332a12c17 dax: follow DAX equality and the documented CROSSFILTER contract (#2228) 2026-11-05 02:28:10 -05:00
alosslessdev eebfbf5d66 dax: give each evaluator family its own registry marker line (#2228) 2026-11-05 02:14:39 -05:00
alosslessdev 40350bad7a dax: fix the evaluator core's rounding, aggregation types, blank member and IN semantics (#2228) 2026-11-05 02:12:24 -05:00
alosslessdev c24fe0d105 dax: bind every documented CROSSFILTER direction and RANK reset keyword (#2228) 2026-11-05 02:12:23 -05:00
alosslessdev 4e2fe3206e dax: find relationship cycles that close through a bidirectional reverse edge (#2228) 2026-11-05 02:12:22 -05:00
alosslessdev faab395ce4 dax: align the README and validate docs with the implemented surface (#2228) 2026-11-05 02:12:21 -05:00
dotCooCoo 5c9f1b757a Merge main into feat/chart-100-stacked-line 2026-11-04 22:45:50 -08:00
dotCooCoo 3ca82dd1e6 Merge main into feat/fill-linear-growth-trend 2026-11-04 22:26:21 -08:00
alosslessdev 4ff74072db dax: keep the SUMMARIZE subtotal row context beside the evaluator's other row state (#2228) 2026-11-05 00:53:35 -05:00
alosslessdev a7abddee7d dax: evaluator, storage and pivot test suites (#2228) 2026-11-05 00:36:54 -05:00
alosslessdev 81a593dbcf dax: scalar values, columnar storage, evaluator framework and scalar core (#2228) 2026-11-05 00:36:53 -05:00
alosslessdev a89acaa9a6 dax: static types, binder and call validation (#2228) 2026-11-05 00:36:35 -05:00
alosslessdev 5c0e27c556 dax: function catalog for every dax.guide category (#2228) 2026-11-05 00:36:34 -05:00
alosslessdev 4f6500320d dax: lexer, Pratt parser, AST, canonical printer and query statements (#2228) 2026-11-05 00:36:28 -05:00
alosslessdev d049f1a595 dax: crate scaffolding, README and workspace wiring (#2228) 2026-11-05 00:36:27 -05:00
TheRenegadeDev f0de6913d1 #2641: Assert every large Values filter choice
Strengthen the existing fixture to check the complete sorted list and checkbox states. Production, docs, manifests and lock unchanged. Engine integration113, strict engine Clippy, fmt and diff checks pass. Required aggregate CI stops only at unchanged Windows CLI check.rs281; later aggregate stages skipped.
2026-11-04 23:01:12 -06:00
TheRenegadeDev 1baac9125c #2641: Put the parity revision entry in its history table
Move the existing Nov4 row intact out of Window and chrome. All other lines and all production/test/dependency trees are identical to the preceding head. Structural and fmt checks pass; required aggregate CI still stops only at the unchanged Windows CLI lint. Runtime suites are not repeated for this documentation-only move.
2026-11-04 22:54:44 -06:00
TheRenegadeDev c01eb6cd2a #2641: Preserve active filter choices and index Values matching
Root verified both findings, red/green regression, matcher semantics and all five quality axes; see review-4476435045-decisions.md. No additional delegate for small confirmed fixes.

Fourteen scoped steps pass on the recorded tree, including engine/UI suites, strict Clippy and standalone gates. Required aggregate CI stops only at unchanged Windows CLI check.rs281; later stages skipped. Fresh hosted validation pending.
2026-11-04 22:24:34 -06:00
AnhNgoo 3131f30f5c fix(ui): prevent Enter from dismissing dialog errors (#2189) 2026-11-05 11:07:39 +07:00
TheRenegadeDev b2cb4eb91f #2641: Integrate form controls and filter protection updates
Preserve cascading eligibility, full-column Apply and per-window pending filter edits. Keep all108 incoming non-union paths and each parent hunk in the four automatic code/test unions, including main clear/reapply protection and control fields/menu registration. Combine parity header and histories without changing filter behavior or dependencies.

Fourteen scoped checks pass on 5bc84f47: full UI1172/296, native15, engine111/863, math8, strict engine/UI Clippy and standalone gates. Three medium R13 reviews read and root-adjudicated; no required introduced fix. Required local aggregate stops only at unchanged Windows CLI check.rs281; later stages skipped. Fresh hosted CI pending.
2026-11-04 21:45:00 -06:00
vangel76andClaude Sonnet 5.5 baff2e50cc Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-05 04:21:06 +01:00
vangel76andClaude Sonnet 5.5 335109beb5 Quick Analysis: assert the multi-area error text
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-05 02:16:37 +01:00
vangel76andClaude Sonnet 5.5 4b65b85b23 Quick Analysis: keep results outside the selection, refuse multi-area, plain Ctrl+Q only
- analysis.addTotal / addSparklines place results beyond the selection's own far edge, so a
  selection reaching past the data no longer gets its totals inside it.
- Both commands refuse a multi-area selection when no range is given.
- Ctrl+Shift+Q and Ctrl+Alt+Q no longer toggle the popup.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-05 02:13:51 +01:00
vangel76andClaude Sonnet 5.5 155d254977 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-05 02:05:08 +01:00
MarekSpodBiedry b006c956eb Print: measure overflowing text with the look it is drawn with, table and conditional formats included (#2333) 2026-11-04 08:07:16 +01:00
MarekSpodBiedry 6fb9b5cc3d Wayland: test that the synthetic End is inserted before the plain wheel move (#2213) 2026-11-04 08:07:13 +01:00
MarekSpodBiedry 3fb6f4334e Merge origin/main into issue-2213 (#2213) 2026-11-04 08:07:05 +01:00
MarekSpodBiedry 8ad676b85c Merge origin/main into issue-2333 2026-11-04 08:06:37 +01:00
AnhNgoo b1a1eee435 fix: use Unicode case-insensitive matching in AutoFilter (#2912) 2026-11-04 13:13:50 +07:00
alosslessdev 7a19af93dd Conditional formatting: translate the formula preset labels in every catalog (#1822) 2026-11-03 23:43:16 -05:00
alosslessdev 68d54cc1b6 Conditional formatting: name the calling command in style errors and title the edit path (#1822) 2026-11-03 23:07:09 -05:00
dotCooCoo 5b6c4a0739 Docs: the fill-handle row lists Linear Trend and Growth Trend 2026-11-03 16:28:08 -08:00
dotCooCoo 839c35635a Merge main into feat/fill-linear-growth-trend 2026-11-03 16:21:28 -08:00
alosslessdev a8e5fdcb75 Merge main into feat/color-scale-editor (#1822)
Port the colour-scale rule editor onto main's split modules: the editor
lives in dialogs/cond_format_rules.rs (rule-type list, per-stop
type/value/colour, style switch, theme-colour keeping) with
ok_cancel_enabled, and cf_menu in ribbon/home.rs gains More Rules… and
opens the rule-type list from New Rule…. The engine's stops/edit
parsing and tests merge unchanged. Catalogs get the rule-editor keys in
every language.
2026-11-03 19:17:16 -05:00
Harrison Booth 61e3275c42 Merge remote-tracking branch 'upstream/main' into gc-fix-deps 2026-11-03 18:09:43 -06:00
Harrison Booth d2e97a485c Merge remote-tracking branch 'upstream/main' into gc-b09-excel-open-check 2026-11-03 18:09:01 -06:00
Harrison Booth ed365d9502 Keep workbook XML writer within lint limits 2026-11-03 16:14:39 -06:00
Harrison Booth 73037efbc5 Make pivot writer binding mutable 2026-11-03 16:08:21 -06:00
Harrison Booth e5c66c0c56 Extract XLSX workbook XML writer helper 2026-11-03 16:05:02 -06:00
Harrison Booth 6856c3cfdf Split XLSX workbook validation from writer 2026-11-03 15:55:30 -06:00
Harrison Booth 25715e77c3 Format filtered table selection helper 2026-11-03 15:52:47 -06:00
Harrison Booth 493ceae678 Merge upstream main into PivotTable pass-through branch 2026-11-03 15:50:40 -06:00
Harrison Booth 4ae322a973 Merge upstream main into quick-xml update 2026-11-03 15:07:51 -06:00
Harrison Booth f954ca72b2 Merge remote-tracking branch 'origin/main' into gc-fix-deps 2026-11-03 15:07:31 -06:00
Harrison Booth b346a5fcce Merge upstream main into Excel open check 2026-11-03 15:06:17 -06:00
Harrison Booth e1ae4d55ce Merge remote-tracking branch 'origin/main' into gc-b09-excel-open-check 2026-11-03 15:04:42 -06:00
Harrison Booth 2be4be9dd2 Reduce dialog display complexity 2026-11-03 15:04:18 -06:00
Vedran DobosandClaude Opus 5.5 dd55a1f4ce Merge upstream main (df137b8e) into format-widens-columns
# Conflicts:
#	crates/engine/src/cmd/format.rs
#	crates/model/src/features.rs
#	docs/decisions.md
#	docs/file-format-parity.md
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:56:16 +01:00
Vedran DobosandClaude Opus 5.5 d8be9537ac Merge upstream main (df137b8e) into csv-sep-line
# Conflicts:
#	crates/engine/src/io.rs
#	crates/xlsx/src/csv.rs
#	docs/decisions.md
#	docs/file-format-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:51:53 +01:00
Vedran DobosandClaude Opus 5.5 58f4a5d6f3 Merge upstream main (df137b8e) into autofit-test-real-font
# Conflicts:
#	crates/engine/src/cmd/format.rs
#	docs/ui-parity.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 21:49:31 +01:00
Harrison Booth a4094cc173 Merge upstream main into write reservation support 2026-11-03 14:37:53 -06:00
Harrison Booth 7b758ef1c3 Merge upstream main into table filter round trip 2026-11-03 14:00:12 -06:00
Harrison Booth 2de9f32d4b Merge upstream main into exact number sorting 2026-11-03 13:48:54 -06:00
Harrison Booth e27bb51c58 docs: clarify XLSX Data Model preservation 2026-11-03 13:46:17 -06:00
Harrison Booth c69969fbfc Merge upstream main into extLst passthrough 2026-11-03 13:26:15 -06:00
zyzabruh 475019d69c Merge origin/main into paste-transpose-refs 2026-11-03 20:21:54 +01:00
Harrison Booth a7b39a0ed3 Merge upstream main and optimize table spill reads 2026-11-03 13:18:08 -06:00
Harrison Booth 379c6e2265 Merge upstream main and finish array entry review fixes 2026-11-03 13:16:28 -06:00
Harrison Booth f81a8d84b2 Merge upstream main and verify IRR convergence 2026-11-03 13:14:31 -06:00
Harrison Booth 5168a1c9c7 Merge upstream main and finish selection review fixes 2026-11-03 13:11:56 -06:00
Harrison Booth 1ac75eb858 Correct Unicode concat boundary expectation 2026-11-03 11:59:43 -06:00
Harrison Booth 5f4f5ce4c5 Count Excel text limits in UTF-16 units 2026-11-03 11:43:58 -06:00
Harrison Booth 1e8541d050 Merge upstream main into text-cap branch 2026-11-03 11:42:26 -06:00
TheRenegadeDev 5aac662668 #2641: Integrate current grid and workbook updates
Preserve cascading eligibility, full-column Apply and per-window pending filter edits. Keep all115 incoming non-union paths and each parent hunk in the five automatic code/test unions. Combine parity header and histories without changing filter behavior or dependencies.

Fourteen scoped checks pass on fe7e6bc8: full UI1150/291, native15, engine111/828, math8, strict engine/UI Clippy and standalone gates. Three medium R12 reviews read and root-adjudicated; no required introduced fix. Required local aggregate stops only at unchanged Windows CLI check.rs281; later stages skipped. Fresh hosted CI pending.
2026-11-03 09:44:00 -06:00
Higgs32584andClaude Opus 5.5 d9d9e3c628 Merge origin/main into fix/print-image-copies-budget; track image bytes incrementally
Keep a running count of retained image bytes so add_page and page_mut no
longer scan every page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 09:46:27 -05:00
vangel76andClaude Sonnet 5.5 8516e5fd0d Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-02 23:40:36 +01:00
dotCooCoo b4beded739 Fill handle: a Python cell is not a Linear Trend or Growth Trend source 2026-11-02 14:27:54 -08:00
dotCooCoo 9c5b6b2dbe Charts: data table keys for 100% stacked line charts use line swatches 2026-11-02 14:25:28 -08:00
Sebastian Whincop b815f11184 Merge remote-tracking branch 'upstream/main' into fix/excel-snap-to-zero 2026-11-03 11:04:11 +13:00
dotCooCoo 78f0b47b43 Merge main into feat/fill-linear-growth-trend 2026-11-02 14:01:03 -08:00
dotCooCoo 6e2bf00b14 Merge main into feat/chart-100-stacked-line 2026-11-02 14:01:03 -08:00
TheRenegadeDev eb94d99326 #2641: Integrate RefEdit and Wayland main updates
Preserve the cascading-filter implementation, per-window pending state and cached-Python regression unchanged. Combine RefEdit test registration and parity summaries/history. Keep all34 incoming non-union paths, main Linux X11/Wayland features, lock and15-second math gate.

All36 scoped checks pass on tree77040605, including engine111/798, filter19, RefEdit53+4, math8, both strict Clippy runs and WASM. Three medium source reviews completed and root-adjudicated; no introduced blocking defect. Local aggregate stops at unchanged Windows CLI check.rs281; later stages skipped. Fresh hosted CI pending.
2026-11-02 14:57:02 -06:00
vangel76andClaude Sonnet 5.5 d2a608c750 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-02 19:54:19 +01:00
Neil Cawse 25b01d9497 Merge upstream main into fix/pivot-refresh-fidelity 2026-11-02 18:11:04 +00:00
Neil Cawse 2f7e6bf878 Merge upstream main into fix/pivot-chart-series and address review comments 2026-11-02 18:10:08 +00:00
TheRenegadeDev a738b160db #2641: Integrate Python cached results with filter queries
Merge main9172516a, retaining all106 non-union incoming blobs and the unchanged cascading-filter implementation. Preserve data exports, both UI test-module lists, both parity summaries and every history row. Add a read-only cached-Python filter/selection regression without executing code or changing the sorter.

All33 scoped checks pass on treee5cebb5b: engineIT111/lib798, filter19, Python mode16/edit4/hidden4, editor19, native15, strict engine/UI Clippy, WASM and gates. Three exact-medium R10 reviews of70f found no production defect and one shared test-order issue; root corrected two expected lists and reran validation. Initial linker failure on full C: was retained and retry passed with E: task temp. Aggregate stops at unchanged Windows CLI check.rs281; later stages skipped. Hosted checks pending; no dependency/workflow/asset/credit edits.
2026-11-02 11:57:34 -06:00
TheRenegadeDev be0b6232e8 #2641: Integrate equations and platform shortcut metadata
Merge main6f52cc50 while preserving cascading choices, full-column Apply/search and per-window pending filter state. Keep main's group/ungroup Mac metadata, the filter_selection export, both equation/cascading test modules and both parity summaries/history. All eight non-overlapping feature blobs match6d3c10bb; all92 incoming non-union paths match main. Inherited math dependency graph remains main's.

Three fresh exact-medium Opus5.5, Sol6.1/default-tier and Grok4.7 R9 reviews have no actionable findings after independent root adjudication. All29 scoped checks pass: filter19 including two-window/search/Apply, engineIT110/lib744, equation7, palette/dialog-focus10, strict engine/UI Clippy and WASM. Required local CI stops only at unchanged Windows CLI check.rs281 lint and skips later stages. New-head hosted CI remains required; no authored dependency, workflow, asset or credit changes.
2026-11-02 09:21:38 -06:00
Ngô Quốc Anh a1fc982132 test(chart): make XLSX roundtrip fixture compatible with newer Chart fields 2026-11-02 16:55:15 +07:00
AnhNgoo 8c0f60ec96 test(filter): align dropdown blank-group assertion 2026-11-02 16:41:59 +07:00
AnhNgoo 8e0d621a0f fix(chart): preserve Excel styles and line weights 2026-11-02 16:31:31 +07:00
TheRenegadeDev 6d3c10bbf2 #2641: Integrate floating objects and Solver report main
Merge main3379f12a while retaining cascading filter choices, full-column Apply/search overlay and per-window pending popup state. Keep typed object drag/selection, hidden-object cleanup, both test module lists and both parity histories. Preserve the standalone AutoFilter integration-gap section. Six feature blobs are unchanged and all58 incoming paths outside five explicit unions match main.

Three fresh exact-medium Opus5.5, Sol6.1/default-tier and Grok4.7 R8 reviews found no actionable findings after independent parent adjudication. All27 scoped checks pass: engineIT110/lib726, filterUI19 including two-window state and search/Apply, objects13, interaction65, native15, strict engine/UI Clippy and fmt/assets/layers/WASM/keytips/parity. Required local aggregate CI stops only on unchanged Windows CLI check.rs281 lint; new-head hosted CI remains required. No authored dependency, workflow, asset or credit changes.
2026-11-02 03:29:00 -06:00
AnhNgoo 5f55b755fa fix(filter): align blank filtering with Excel behavior 2026-11-02 15:21:34 +07:00
Tống Huy Sơn 1f3c7a3390 i18n(vi): expand Vietnamese catalog to full 1,170-entry parity 2026-11-02 14:01:29 +07:00
dotCooCoo a97d858b9e Merge main into feat/fill-linear-growth-trend 2026-11-01 21:34:12 -08:00
dotCooCoo 5f1e609a69 Charts: 100% stacked line kinds keep data tables 2026-11-01 21:20:58 -08:00
dotCooCoo e69515aff1 Merge main into feat/chart-100-stacked-line 2026-11-01 21:12:38 -08:00
TheRenegadeDev 6c447a8082 #2641: Clarify AutoFilter documentation scope
Move the AutoFilter population discussion into its own section before Keyboard while leaving Shortcut audit under Keyboard. State explicitly that separate table dropdowns outside the active sheet AutoFilter columns remain empty, retaining the separate #2506 activation/roundtrip scope. Update the existing feature history entry. Addresses both outside-diff comments in CodeRabbit5732175733.

Documentation only; implementation, tests, dependencies, credits and workflows unchanged. Formatting/parity checks pass. Required local CI hits only the unchanged Windows CLI lint; actual preceding c9 Ubuntu run passed all10 gates and lock verification. New-head hosted CI remains required. Small review findings fixed directly without new agents or tests.
2026-11-01 22:58:40 -06:00
TheRenegadeDev c9e5cdbf7d #2641: Integrate trace and page-order main
Merge main092e5819 while retaining cascading filter choices, full-column selection overlay and window-owned pending popup state. Resolve parity header/history by retaining both parents. Automatic GridState/show and integration-module unions preserve incoming Trace Error, zoom retention, chart tables, Page Setup page order and Solver code. Six feature blobs are unchanged; all82 incoming paths outside explicit unions match main.

Three fresh exact-medium Opus5.5, Sol6.1/default-tier and Grok4.7 reviews have no actionable findings after independent adjudication. Fresh engineIT110/lib674, filterUI19 including two-window preservation, popup6, trace arrows12, zoom12 and collateral UI pass. Strict engine/UI Clippy and fmt/assets/layers/WASM/keytips/parity pass. Required local CI stops only at unchanged Windows CLI recursion lint; new-head hosted CI remains required. No authored dependency, credit or workflow changes.
2026-11-01 22:39:54 -06:00
dotCooCoo fb68684795 Merge main into feat/fill-linear-growth-trend 2026-11-01 17:38:20 -08:00
dotCooCoo 6b34b6c6a8 Merge commit 'refs/check/merge-gridcraft-2602-main' into merge-2602
# Conflicts:
#	ROADMAP.md
2026-11-01 17:21:38 -08:00
Neil Cawse c122e5f893 Merge upstream main into fix/pivot-chart-series 2026-11-02 00:48:11 +00:00
Neil Cawse 80f29610ee Merge upstream main into fix/pivot-refresh-fidelity 2026-11-02 00:47:39 +00:00
TheRenegadeDev 4595d8dace 2641: integrate Function Library and view-mode undo main
Keep main29b17a6f and the verified window-owned filter popup correction.
Resolve the parity document by retaining both histories and behaviors.
All eight feature/correction source and test blobs match local9fbd95e0.

Three fresh exact-medium integration reviews report no actionable defects.
Fresh engine IT101/lib653,filter19,popup6,keyboard12,function-library10,
file-menu20,native12 and strict engine/UI Clippy,fmt,assets,layers,WASM,
keytips/parity pass on frozen tree2b4f5b44 with unchanged lockfile.

Required local CI still stops only on main's unchanged Windows CLI
only_used_in_recursion lint at check.rs281. New-head hosted CI remains
required; no live OS/hardware/counterpart verification is claimed.
2026-11-01 13:11:56 -06:00
TheRenegadeDev 9fbd95e037 2641: merge main and keep pending filter edits with their window
Preserve main69177881 and both parity histories. Move the filter popup's
pending checkbox, search and button state into existing per-window
GridState so another window's column switch cannot delete those edits.
Existing popup-close and window lifecycle own the cache lifetime.

Grok's R5 finding was independently reproduced: the same real UI test
passes exact main production, fails the reviewed candidate, and passes
the correction. Opus and Sol no-findings do not override that proof.
No extra delegate for this small finding. Fresh before/after renders
retain the search and unchecked choice without applying a filter.

19 filter,6 popup,12 keyboard,12 native and20 file-menu tests pass, plus
strict UI Clippy,fmt,assets,layers,WASM,keytips/parity. Engine96/lib646
and engine Clippy source/graph are unchanged from their passing run.
Required local CI still stops only on main's Windows CLI check.rs281
recursion lint; later aggregate steps skip. Hosted new-head CI required.
2026-11-01 12:54:52 -06:00
TheRenegadeDev 0de56624d5 2641: cover header-only filter tables and manual visibility
Exercise the real engine and header-button popup with a genuine header-only table. Verify that its installed AutoFilter offers neither header values nor a phantom blank row, and that the popup dismisses normally. Strengthen the existing manual-hide case to check exact values and selection state.

Production filter matching, selection merging and popup caching are unchanged. Ten focused engine, eighteen filter UI and six popup tests, formatting and strict changed-target Clippy pass. Required aggregate CI retains the unchanged baseline Windows CLI lint failure; exact-new-head hosted CI remains pending.
2026-11-01 01:05:32 -05:00
kezmdorandClaude Opus 5.5 af4f17184c Formula entry: + before a time stays text, as in Excel
Checked by hand in Excel for the web (English (United States) regional
format): `+1:30` stays text, while `-1:30` is the formula `=-1:30` (rows
1 to 30), `+1/30` and `-1/30` are formulas and `1:30` is a time.
`starts_formula` now leaves a `+` followed by a time to the usual
value parsing, which keeps it as text. Raised by @iluebbe in #2023.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 12:20:56 +01:00
kezmdorandClaude Opus 5.5 921cdc974f AutoSum tests join the it test binary, as main's UI tests do
The module uses the shared harness (`common::builder`, `common::app`), so
it runs with the pinned font set like the other UI tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 11:59:24 +01:00
kezmdorandClaude Opus 5.5 6aa6a9cee8 Merge upstream main into fix/1834-autosum-edit-mode
#2851's caret code for an empty `=SUM()` in `run` is kept as is; it and
`point_last_argument` put the caret in the same place. docs/ui-parity.md
keeps main's rows with this change added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 11:56:58 +01:00
kezmdorandClaude Opus 5.5 73999fcd89 Merge upstream main into fix/2023-plus-minus-starts-formula
docs/ui-parity.md keeps main's rows with this change added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 11:56:19 +01:00
vangel76andCodex bcac6859e3 Merge upstream/main into feat/quick-analysis-791
Keep Quick Analysis and the current checkbox-printing parity note together.

Co-Authored-By: Codex <[email protected]>
2026-10-31 11:22:47 +01:00
dotCooCoo 210b8c9cd6 Fill handle: a linear fit of very small numbers keeps them
The fitted line sums the numbers before dividing by their count, so the smallest doubles no longer round to zero one by one; three cells of 5e-324 continue at 5e-324 instead of 0.
2026-10-30 21:12:21 -07:00
dotCooCoo 1668d576a8 Fill handle: a trend from a lone number copies it unchanged
Linear Trend and Growth Trend from a single number now copy the cell as it is. They used to pass it through the fitted line or the logarithm, which rounded it to 15 digits and moved a value near the largest double (1e308 became 1.00000000000001e308).
2026-10-30 21:08:10 -07:00
TheRenegadeDev 478e21a988 #2641: Preserve search Apply semantics on release main
Merge release main while preserving its formula/function/print fixes, workspace version and packaging. Retain reviewed feature behavior and source pins. All three requested exact medium reviews adjudicated; small accepted findings independently reproduced, fixed and verified directly.

Validation: current production integration and collateral library/UI tests, inspected render, strict scoped Clippy, formatting, WASM and repository gates pass. Required local aggregate CI stops only on the source-identical Windows CLI recursion lint; new-head hosted CI remains pending. See the PR verification for precise counts and limits.
2026-10-30 22:48:04 -05:00
dotCooCoo 7eb044921b Merge branch 'main' into feat/fill-linear-growth-trend
# Conflicts:
#	docs/ui-parity.md
2026-10-30 20:46:55 -07:00
dotCooCoo 7047dca872 Merge branch 'main' into feat/chart-100-stacked-line 2026-10-30 19:33:09 -07:00
dotCooCoo a5e03454a4 Merge branch 'main' into feat/fill-linear-growth-trend 2026-10-30 19:17:12 -07:00
Neil Cawse b3b0ceabae Merge main (1f4c67e) into the branch 2026-10-31 02:07:09 +00:00
vangel76andCodex f3b88ae36b Merge upstream/main into feat/quick-analysis-791
Combine the Quick Analysis parity note with the current upstream UI updates.

Co-Authored-By: Codex <[email protected]>
2026-10-30 22:46:07 +01:00
Harrison Booth 787b12069d Merge remote-tracking branch 'origin/main' into gc-irr-xirr-excel-solver 2026-10-30 16:09:41 -05:00
DerKarussellbremserandClaude Opus 5.5 1836cd83a1 Merge main: the imitated styles move to grid/quadrant.rs and grid/cell_paint.rs
main split grid.rs into grid/, so the painting changes are made again in
the new files. Wrapped text takes bold_dx from its size; the unwrapped and
rotated paths from font.size after Shrink to fit. docs/ui-parity.md keeps
both sides' entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011TXsSUeAGF2oN7zdYuxxu4
2026-10-30 21:56:05 +01:00
TheRenegadeDev ab6a4b4030 #2641: Integrate current main without changing cascading filter behavior
Merge main75f7056e, retain all incoming features, pins and contributor data, resolve parity summary/history conflicts and document Apply preservation. Filter implementation and regressions remain unchanged from the published head.

Validation: engine95, full Windows engine lib638, filterUI16 and overlapping popup6 pass; production dropdown render inspected. Strict scoped Clippy, fmt, WASM11 and repository gates pass. Three exact medium reviews adjudicated with no code findings; one documentation clause clarified. Required aggregate CI stops only on source-identical main Windows CLI recursion lint. New-head hosted CI pending.
2026-10-30 15:17:56 -05:00
Neil Cawse a5d6efab4d Merge main (68a4b1a) into the branch 2026-10-30 11:51:10 +00:00
Neil Cawse b5e831d461 Merge main (68a4b1a) into the branch 2026-10-30 11:51:10 +00:00
AnhNgoo 17abd46b97 fix(filter): address CodeRabbit review findings (#2911) 2026-10-30 16:57:51 +07:00
AnhNgoo 9187049f7f fix(filter): ignore surrounding whitespace in AutoFilter values (#2911) 2026-10-30 15:14:14 +07:00
vangel76andClaude Sonnet 5.5 946b98c375 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-29 23:20:13 +01:00
zyzabruh 14fbd977b7 Merge origin/main into paste-transpose-refs 2026-10-29 20:52:33 +01:00
Harrison Booth 26b9dec45b Merge upstream main into pivot cache branch 2026-10-29 09:07:25 -05:00
dotCooCoo 53228adb7d Fill: Linear Trend fits numbers near the largest double without overflowing
When a source number is larger than 2^600, least_squares multiplies the
numbers by 2^-600 before the fit and multiplies the fitted values and the
step by 2^600 afterward. A source of 1e308 four times and then 0 now
continues at 2e307; before, the covariance sum overflowed and the target
cell showed #NUM!.

The test for numbers near the largest double compares to within 1e-9
instead of exactly, since the rounding to 15 digits of 1e308 gives
1.0000000000000004e308 on Linux.
2026-10-29 04:43:54 -07:00
TheRenegadeDev 743865a836 #2641: Preserve filter selections while integrating the macro interface
Merge main2ff75179 while retaining incoming macro overlays and parity descriptions. Fix reviewed Apply/Enter state loss by merging eligible edits into the full column selection, preserving hidden selected/excluded values and blanks. Add real table/range popup regressions.

Validation: engine92, filterUI16 and6 overlapping popup tests pass;24 new preservation cases cover edited/no-op Enter/Apply. Strict scoped Clippy/fmt/assets/layers/WASM/keytips/parity/doctest checks and inspected render pass. Three exact medium reviews adjudicated; accepted finding reproduced and fixed directly. Aggregate local CI retains only source-identical Windows baseline errors; hosted new-head CI pending.
2026-10-29 05:22:49 -05:00
dotCooCoo 364e48dcab Fill: the trend menu cache has a type alias, as main's clippy settings now require 2026-10-29 03:22:11 -07:00
dotCooCoo a0a2627894 Merge main into feat/fill-linear-growth-trend 2026-10-29 03:09:14 -07:00
AnhNgoo 47c5e3b816 docs(chart): document Cartesian chart rendering 2026-10-29 13:54:59 +07:00
AnhNgoo 9777459eb6 fix(chart): render explicit Excel chart styles 2026-10-29 13:23:50 +07:00
TheRenegadeDev 91e6a41a63 #2641: Discard old filter-menu state when switching columns
Clear the previous column checkbox, search and button caches after the grid interaction changes the open menu. Keep the new menu state intact. The real UI regression fails on the prior production code and passes with the fix.

Validation: filter15, popup6, strict UI all-target Clippy, fmt and WASM pass. Aggregate CI rerun retains only the two unchanged Windows baseline diagnostics. Small CodeRabbit finding validated and fixed directly after the three medium merge-resolution reviews.
2026-10-28 23:50:52 -05:00
TheRenegadeDev 5378f80672 #2641: Preserve cascading filters and slicer criteria on current main
Port the shared criterion evaluator and lazy dropdown initialization into the extracted modules. Preserve representable criteria written by existing slicers even when their column lies outside the sheet filter columns, retaining checked addition.

Validation: Engine92 including the RED/GREEN slicer regression; cascading UI case and render passed.
Scoped engine/UI Clippy, formatting, assets, layers, WASM, keytips, parity and workspace doctests pass. Three independent requested medium reviews are adjudicated.

Aggregate CI was run; the remaining Windows CLI recursion lint and Unix-only engine test are byte-identical to current main. Hosted CI remains required. No installs, dependency upgrades or contributor-credit edits.
2026-10-28 23:36:06 -05:00
zyzabruh 437b7f2df0 Merge origin/main into paste-transpose-refs
Two files conflicted. Both are the same story: main's strict Clippy
refactor (#2711) reworked the code the branch sits in.

- paste_special.rs: main moved the `shift` closure out to the top of
  the function and extracted the operations helpers, so the branch's
  old copy of the whole paste block collided with the new shape. Took
  main's version of the file and re-applied the branch's one change on
  top of it: a transposed paste calls `transpose_relative(e, sc, dest)`
  where an ordinary paste still shifts. `git diff origin/main` on that
  file is now exactly that single hunk.
- tests.rs: main converted the suite from `unwrap()` to returning
  `Result` and `?`; `copy_transpose` is written in that style too.
2026-10-29 02:19:43 +01:00
Higgs32584andClaude Opus 5.5 8893ead179 Merge origin/main into fix/print-image-copies-budget
Resolve conflicts with the strict-Clippy refactors (287acf7a, 9717ccba):
image_rgba now takes a Rect and [w, h] pixel size; explicit super imports
replace the glob; main's PicCache alias gives way to the PR's capped cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 14:29:01 -04:00
Harrison Booth cd6fe4f8bd Extract file sharing XML writer 2026-10-28 12:05:24 -05:00
Harrison Booth a276e2f21d Allow keyboard dispatch complexity 2026-10-28 12:04:36 -05:00
Harrison Booth 496aa28ed3 Fix pivot cache eligibility filtering 2026-10-28 12:03:33 -05:00
Harrison Booth 2506ba3ddb Factor kept style patch type 2026-10-28 12:01:57 -05:00
Harrison Booth 15eef6b434 Extract XLSX write validation helper 2026-10-28 11:59:52 -05:00
Harrison Booth 3b8daf900c Split grid keyboard focus guard 2026-10-28 11:56:25 -05:00
Harrison Booth 2295cc71c6 Remove unused filter region import 2026-10-28 11:51:45 -05:00
Harrison Booth 2c976a6e6b Import engine error in file commands 2026-10-28 11:51:09 -05:00
Harrison Booth 4efd8fc0db Qualify selection mode references 2026-10-28 11:47:41 -05:00
Harrison Booth 40268a3c67 Merge upstream main into gc-f8-extend-add-selection 2026-10-28 10:32:41 -05:00
Harrison Booth cc2229a08b Merge upstream main into table spill handling 2026-10-28 10:29:36 -05:00
Harrison Booth 2c6ba8a658 Merge upstream main into extension passthrough 2026-10-28 10:28:58 -05:00
Harrison Booth 1396236440 Merge upstream main into pivot data model caches 2026-10-28 10:25:51 -05:00
Harrison Booth 6531650600 Merge upstream main into exact number sorting 2026-10-28 10:25:12 -05:00
Harrison Booth c998ff1ffb Merge upstream main into filtered subtotal export 2026-10-28 10:23:58 -05:00
Harrison Booth dac313337d Merge upstream main into password protection 2026-10-28 10:22:18 -05:00
Harrison Booth 2c4f471566 Import Arc in lambda evaluator 2026-10-28 10:20:38 -05:00
Harrison Booth 6a15912b06 Replace lambda wildcard import 2026-10-28 10:17:05 -05:00
Harrison Booth 96ae211258 Merge remote-tracking branch 'upstream/main' into upkeep/gc-fix-lambda
# Conflicts:
#	crates/calc/src/eval/call.rs
#	crates/calc/src/eval/lambda.rs
2026-10-28 10:09:42 -05:00
dotCooCoo 04f8797ee4 XLSX: a 100% stacked line group with mixed markers opens with each series' own markers
A single percentStacked line group whose series differ in markers opens as a combo chart, so saving it keeps the marked and unmarked series as they were.
2026-10-28 08:04:56 -07:00
dotCooCoo 9680794bc4 XLSX: combo charts keep each area, marked line and column grouping in its own group when saved
Lines and secondary series are written as one chart group per kind, so areas, lines with markers and columns with different groupings open again as the same kinds instead of plain lines or the first column's grouping.
2026-10-28 08:00:31 -07:00
dotCooCoo 3adf662578 XLSX: combo charts keep secondary columns, lines and 100% stacked lines in separate groups when saved 2026-10-28 06:49:07 -07:00
dotCooCoo a6f9b80e43 Charts: move the marker check out of cartesian to keep it under the complexity limit 2026-10-28 06:39:04 -07:00
dotCooCoo 4d0d3bdbfa Merge commit 'refs/check/r4-gc-main' into p21/gc-2602
# Conflicts:
#	crates/chart/src/render/cartesian.rs
2026-10-28 06:24:03 -07:00
dotCooCoo 4550a1eba7 XLSX: 100% stacked lines on a combo chart's secondary axis keep their kind when saved 2026-10-28 06:10:02 -07:00
dotCooCoo 8e81dade33 XLSX: combo charts keep 100% stacked line series and their order when saved
A combo chart's 100% stacked line series were saved in the plain line
group and reopened as ordinary lines. They now share one percentStacked
group, each with its own markers, and reopening a combo chart puts its
series back in their c:order order.
2026-10-28 06:04:36 -07:00
dotCooCoo b4b89a4e36 Charts: Format Chart Area's Chart Type offers 100% Stacked Line with Markers
The pane's Chart Type section listed 100% Stacked Line but not its marker variant, so a chart of that type showed no current type there and could not be changed to it from the pane.
2026-10-28 04:03:37 -07:00
kezmdorandClaude Opus 5.5 6fe8a65c5c Merge upstream main into fix/1834-autosum-edit-mode
main moved SheetApp's methods from lib.rs to app/: the menu-style AutoSum
case and `auto_sum_in_editor` now sit in app/commands.rs. The editor's
new selection (`anchor`) takes AutoSum's proposed range from
`select_from` when the caret is pushed into the widget. Both new editor
tests are kept; docs/ui-parity.md keeps main's rows with this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 11:18:26 +01:00
dotCooCoo 5846f59081 Fill: the least-squares mean does not overflow for numbers near the largest double 2026-10-28 03:17:15 -07:00
kezmdorandClaude Opus 5.5 a2312fff8b Merge upstream main into fix/2023-plus-minus-starts-formula
main moved the entry functions from cmd/edit.rs to cmd/edit/cell.rs; the
leading-sign rule is applied to `input_to_cell` there. docs/ui-parity.md
keeps main's rows with this change added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 11:16:27 +01:00
dotCooCoo 92dcd308c2 Merge branch 'main' into feat/chart-100-stacked-line 2026-10-28 02:22:02 -07:00
dotCooCoo 2a8cc47a3f Fill: the trend menu check reuses numeric_lanes and Pattern::growth
trend_applies now calls the same lane reader and growth fit as the fill, so the menu offers Linear Trend and Growth Trend exactly when the fill accepts them.
2026-10-28 01:30:43 -07:00
AlissonFAandClaude Opus 5.5 1ccc95d846 #258: a growing table rebuilds the dependencies instead of recalculating everything
From CodeRabbit's review of b83f717: growth ran `recalc_all`, which evaluates
every formula, so entering a row below a table recalculated the whole
workbook even in manual mode (and on every new row in automatic mode).

Growth now sets `Ctx::rebuild_deps` (was `full_recalc`): the commit rebuilds
the dependency graph, so structured references cover the grown range, then
recalculates as any edit does, through `cells_changed` (only the edited
formulas in manual mode). Every cell of the new row or column is marked
changed, empty ones too, so ROWS, COUNTBLANK, COLUMNS and the like over the
table follow the growth.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 23:50:36 -03:00
dotCooCoo 10bbee4047 Merge main into feat/fill-linear-growth-trend 2026-10-27 19:40:17 -07:00
AlissonFAandClaude Opus 5.5 b83f717a39 Merge origin/main into feat/table-auto-expansion
main split cmd/edit.rs into cmd/edit/*.rs (#2690) and renamed cmd/mod.rs to
cmd.rs. The data-entry markers (`cx.entry`) move with their commands:
cell_set, range_set_values and range_fill to cell.rs, paste_text to
clipboard.rs, paste_special to paste_special.rs, and fill_dir, auto_fill,
fill_series and flash_fill to fill.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 23:27:03 -03:00
Harrison Booth cc3858a394 Filter: a range over only some of the active table's columns is refused too 2026-10-27 18:01:50 -05:00
Harrison Booth cf17534e7b Filter test: the sheet-prefix table toggle names the whole table, as a partial range over a table is refused 2026-10-27 17:47:30 -05:00
Harrison Booth 7e643e2930 Merge remote-tracking branch 'origin/gc-subtotal-filtered-rows-roundtrip' into gc-subtotal-filtered-rows-roundtrip 2026-10-27 17:33:27 -05:00
Harrison Booth dbacb4cc80 Filter: refuse a partial range over the active table; filtering a table re-enables its buttons 2026-10-27 17:33:24 -05:00
Harrison Booth 7b83509a93 Filter test: build the table rows outside json! so the test compiles 2026-10-27 17:28:43 -05:00
Harrison Booth f3c214b2dd Filter: turning a table's filter off hides the union of the other tables' excluded rows and recalculates 2026-10-27 17:23:24 -05:00
Harrison Booth a2e3f265c0 Filter: turning a table's filter off re-evaluates the criteria of the tables that keep one 2026-10-27 17:12:04 -05:00
Harrison Booth 10115f41ed XLSX: name the type of the kept cache list 2026-10-27 17:03:15 -05:00
Harrison Booth d57d5cf267 XLSX: keep the cache of a kept PivotTable that names it only by cacheId 2026-10-27 16:57:20 -05:00
Harrison Booth be8efa6d0b Filter: turning a table's filter off keeps rows another table's criteria still hide 2026-10-27 16:46:18 -05:00
Harrison Booth 2cdffc6282 XLSX: drop kept PivotTables that name a dropped cache by id; hash sets for style references 2026-10-27 16:45:35 -05:00
Harrison Booth 2e1a744c6c Filter: turning a table's filter buttons off also drops the sheet AutoFilter on it, and a disabled table filter saves no criteria 2026-10-27 16:24:32 -05:00
Harrison Booth 8ec8445b5a Resize Table: read the active sheet through its method after the merge 2026-10-27 16:22:20 -05:00
Harrison Booth 0b31398c0d Filter: a table filter must reach the table's last data row, and the table part keeps only such filters 2026-10-27 16:20:32 -05:00
Harrison Booth fb19a4fb87 Table results: keep one-value spills out of the range-aggregate spill check 2026-10-27 16:19:51 -05:00
Harrison Booth d479ff2f4b Merge upstream main into gc-fix-lambda
# Conflicts:
#	crates/calc/src/eval.rs
2026-10-27 16:18:38 -05:00
Harrison Booth 843e09fb77 Port the PivotTable keep-on-save code into the split passthrough modules 2026-10-27 16:18:00 -05:00
Harrison Booth f4e7a1e33f Merge main into the PivotTable data connection / Data Model change 2026-10-27 16:16:29 -05:00
Harrison Booth d853b05dbd Merge upstream main into gc-fix-text-cap
# Conflicts:
#	crates/calc/src/eval.rs
#	crates/engine/src/cmd/edit.rs
2026-10-27 16:15:37 -05:00
Harrison Booth 73d36eef04 Merge remote-tracking branch 'origin/main' into gc-fix-text-cap 2026-10-27 16:13:54 -05:00
Harrison Booth 7a3f75d7c3 Merge remote-tracking branch 'upstream/main' into gc-a24-password-to-modify
# Conflicts:
#	crates/ui-egui/src/dialogs.rs
#	crates/ui-egui/src/lib.rs
2026-10-27 16:13:52 -05:00
Harrison Booth db21e558d1 Merge remote-tracking branch 'upstream/main' into gc-subtotal-filtered-rows-roundtrip
# Conflicts:
#	crates/engine/src/cmd/data.rs
#	crates/xlsx/src/sheet_write.rs
2026-10-27 16:08:57 -05:00
Harrison Booth 8211e218ce Merge remote-tracking branch 'upstream/main' into gc-table-resize-overlaps
# Conflicts:
#	crates/engine/src/cmd/extra.rs
2026-10-27 16:07:24 -05:00
Harrison Booth 2f744078ec Merge upstream main into gc-fix-2335-table-spill
# Conflicts:
#	crates/calc/src/recalc.rs
2026-10-27 16:03:25 -05:00
Harrison Booth ef732f04ce Merge upstream main into gc-array-entry-marks-all-cells
# Conflicts:
#	crates/engine/src/cmd/edit.rs
2026-10-27 16:02:46 -05:00
Harrison Booth f300a41236 Merge upstream main into gc-irr-xirr-excel-solver
# Conflicts:
#	crates/functions/src/financial.rs
2026-10-27 16:01:34 -05:00
Harrison Booth f4049f9e49 Merge upstream main into gc-f8-extend-add-selection
# Conflicts:
#	crates/ui-egui/src/grid.rs
#	crates/ui-egui/src/lib.rs
2026-10-27 15:59:25 -05:00
Harrison Booth 5c987d1eae Merge remote-tracking branch 'upstream/main' into gc-extlst-passthrough
# Conflicts:
#	crates/xlsx/src/passthrough.rs
2026-10-27 15:59:05 -05:00
vangel76andClaude Sonnet 5.5 4d0074e5cf Merge upstream/main into feat/quick-analysis-791
Main moved the app commands, grid drawing and shortcuts into submodules; the Quick Analysis hooks are re-applied there.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-27 20:13:23 +01:00
Harrison Booth efac07d32f Merge main into gc-fix-deps (carry the quick-xml 0.42 edits into the split check/ and passthrough/ modules) 2026-10-27 09:17:04 -05:00
Neil Cawse af3b87e965 Merge main (45f5ab1) into the branch 2026-10-27 11:39:52 +00:00
zyzabruh 9dae419df2 Merge origin/main into paste-transpose-refs
`main` split `cmd/edit.rs` into `cmd/edit/*.rs`, so both hunks of the branch
moved: `paste_special` kept the `shift_relative` call the branch turns into a
transposition, and the inline `mod tests` became `cmd/edit/tests.rs`.

Resolution: take `main`'s `cmd/edit.rs` — the branch touched nothing else in
the code `main` moved out of it — then re-apply both hunks where they now
live: the `transpose` branch in `cmd/edit/paste_special.rs`, and the two tests
in `cmd/edit/tests.rs`, beside the existing transposed-paste overshoot test.
`crates/formula/src/adjust.rs` and its tests were untouched by `main` and came
through the merge byte for byte.

Against `main` the merge carries the whole of #2606 (six files) and against the
branch tip it carries all of `main`; no hunk from either side was dropped.

Checks: `cargo test -p gridcraft-formula -p gridcraft-engine` (502 + 83 engine
lib and integration, `cmd::edit::tests::transposed_paste_*` and
`tests::copy_transpose` among them; 34 + 8 formula), `cargo fmt -p
gridcraft-engine -p gridcraft-formula -- --check`, `cargo clippy -p
gridcraft-engine -p gridcraft-formula --all-targets --all-features -- -D
warnings`. `cargo xtask ci` cannot run on Windows: the engine's
`save_fails_upfront_when_the_temp_name_is_taken` test compiles
`std::os::unix::fs::symlink` without a `#[cfg(unix)]` guard (#2541); it was
guarded locally to run the suite, and the guard is not part of this commit.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-10-27 11:59:43 +01:00
Higgs32584andClaude Opus 5.5 f0397d5f5b Security: PDF export keeps a bounded amount of picture data, however many pages a picture spans
render_pdf memoized picture decodes, but each page a picture overlapped still kept its own
RGB copy until the document was written, with no document-wide bound: a 3 KB workbook with
one large-extent picture grew ~29 MiB per page and passed 2 GiB in seconds (MAX_PAGES is
2000). PdfDoc now has a document-wide image budget (MAX_DOC_IMAGE_BYTES, 512 MiB) checked
before anything is allocated; pictures past it are left out, as oversized ones already are.
Cell-picture decodes are memoized too. Complements the write-time dedupe of #818 (#816).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 00:51:17 -04:00
Neil Cawse e1a5244c0c Merge main (45f5ab1) into the branch 2026-10-27 02:55:01 +00:00
Vedran DobosandClaude Opus 5.5 19bc9660ff Tests: header_autofit reads the active sheet through Workbook::active_sheet()
Main now keeps the active sheet in an ActiveSheet; the test took the field as an index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 21:29:31 +01:00
Vedran Dobos b7547111f3 Merge upstream main (d8c5f588) into format-widens-columns
# Conflicts:
#	docs/ui-parity.md
2026-10-26 20:31:28 +01:00
Vedran Dobos a19b16f211 Merge upstream main (d8c5f588) into autofit-test-real-font
# Conflicts:
#	docs/ui-parity.md
2026-10-26 20:31:27 +01:00
TheRenegadeDev 1fcaffe7b7 #2641: address review coverage and menu scan cost 2026-10-26 13:40:03 -05:00
TheRenegadeDev a7a708d0f6 #2641: cascade AutoFilter dropdown values 2026-10-26 13:22:28 -05:00
Harrison Booth 7369738a28 Dependencies: quick-xml 0.41 to 0.42 (names, values and text are &str) 2026-10-26 12:36:07 -05:00
Harrison Booth 01da1806d1 Evaluate an array IF condition once, release captured closures in a loop, update wrapped-call test 2026-10-26 12:18:32 -05:00
Harrison Booth 2fbe96820c Cap range.setValues text when parse is false 2026-10-26 12:07:19 -05:00
Harrison Booth abf93c2e23 Run LAMBDA tail calls in a loop so tail recursion reaches Excel's depth 2026-10-26 12:01:09 -05:00
Harrison Booth 9bbcb7ce90 Excel open check: compile the helper before Excel starts so the PID line is not held up 2026-10-26 11:44:00 -05:00
Harrison Booth 7155ced916 Cap text after parsing the apostrophe prefix and in text-formatted cells; keep CONCATENATE errors past the cap 2026-10-26 11:42:21 -05:00
Harrison Booth 571bdf68ad Keep the clipboard budget test within the cell limit 2026-10-26 11:30:59 -05:00
Harrison Booth c4920c463b Excel open check: count saved passes apart from the XLM gate 2026-10-26 11:30:56 -05:00
Harrison Booth 0ddd8684ef Move cap_text above the test module 2026-10-26 11:24:42 -05:00
Harrison Booth 15661dc973 Cap text at 32,767 characters like Excel: & and CONCATENATE cut, CONCAT and TEXTJOIN give #CALC!, cell.set and CSV fields cut (#2635) 2026-10-26 11:13:15 -05:00
Harrison Booth 1053b66a0e Excel open check: literal paths for saved workbooks and the input folder 2026-10-26 11:12:32 -05:00
Harrison Booth b023410ca4 Excel open check: skip workbooks with Excel 4.0 macro sheets, require a zero CLI exit before opening the saved file 2026-10-26 10:55:56 -05:00
Harrison Booth 7a8b2261f8 Array entry of a formula marks every result cell changed, stored or not 2026-10-26 10:20:01 -05:00
Harrison Booth dacff8ff97 IRR: an exact root with a zero slope is the answer, as in Excel 2026-10-26 10:10:26 -05:00
Harrison Booth c708afad34 Array entry of a constant fills every cell and forms no array
Ctrl+Shift+Enter over a multi-cell selection with a plain value puts that value in every cell, as Excel does; formulas still become arrays.
2026-10-26 10:10:19 -05:00
Harrison Booth 4081acd660 Merge origin/main into gc-array-entry-marks-all-cells 2026-10-26 10:09:45 -05:00
Neil Cawse 712a17f1e6 Merge main (d8c5f58) into the branch 2026-10-26 14:33:29 +00:00
Neil Cawse 077533edb8 Merge main (d8c5f58) into the branch 2026-10-26 14:21:11 +00:00
AlissonFAandClaude Opus 5.5 8af1e4fd84 #258: a column's validation doesn't cover a new-row cell that has its own rule
From CodeRabbit's review of 9319fb4: growing a table stretched the column's
validation over the new row even where a cell already had a rule (pasted with
the entry, or set before), so two rules overlapped and the first one, the
column's, silently replaced the cell's. Only the free cells of the new row
join the column's rule now; a rule over several columns takes in the free
runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 10:22:12 -03:00
AlissonFAandClaude Opus 5.5 9319fb44b4 #258: a ragged pasted block grows a table by all its rows; AutoSum over several cells enters data
From a second bug hunt on #259:
- Table growth runs in two passes over the entered cells: rows first, in
  row order, then columns, in column order. A block whose first row has its
  entry in one column and its second row in another now grows the table by
  both rows (the column-order pass left the second row out).
- AutoSum over a selection enters its totals as data, as AutoSum on one cell
  (through cell.set) already did, so a total right below a table grows it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 10:00:53 -03:00
AlissonFAandClaude Opus 5.5 b56d13da75 #258: only data entry grows a table; fill only calculated columns
From a bug hunt on #259:
- Tables grow only for commands that enter data (cell.set, range.setValues,
  range.fill, fills, AutoFill except Formats, Fill Series, Flash Fill, paste
  that writes content), marked with Ctx::entry, which replaces
  Ctx::formats_only. Sorting the data below a table, moving columns,
  Insert/Delete Cells, Fill > Formats Only and checkboxes no longer pull it
  in. Dragging cells is Cut + Paste, which still counts as entering them.
- A formula fills down only in a calculated column (the first data row holds
  the same formula, moved); a formula typed into one cell isn't copied.
- Below a table with only a header row, the new row takes nothing from the
  header.
- A one-cell array formula stays an array when it fills down.
- The other tables' ranges are collected only for a cell next to a table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:54:59 -03:00
Harrison Booth 260b84d093 Excel open check: a failed probe job is a CRASH, not an error that ends the run 2026-10-26 07:47:06 -05:00
Harrison Booth 9bd604aa12 Correct the dated_flows doc comment for blank cells 2026-10-26 07:45:38 -05:00
Harrison Booth cfcde5bfbd Excel open check: stop only the Excel instance a probe started, found by its window's process id 2026-10-26 07:35:56 -05:00
Harrison Booth 2f86b52706 XNPV test: clone the dates range 2026-10-26 07:33:58 -05:00
Harrison Booth e3fa42607f XIRR and XNPV: match Excel for blank first rows, blank dates, text values and a zero first flow 2026-10-26 07:31:02 -05:00
Harrison Booth 4b86dc9dc9 Merge remote-tracking branch 'origin/main' into gc-fix-2398-excel 2026-10-26 07:29:18 -05:00
AlissonFAandClaude Opus 5.5 fbb33c42ee #258: the formula a new table row takes keeps its dynamic-array mark
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:26:06 -03:00
Harrison Booth 1fe4f79db6 Excel open check: save workbooks with the CLI and open them in real Excel, a repair counts as a failure 2026-10-26 07:22:28 -05:00
AlissonFAandClaude Opus 5.5 55e73b2564 #258: table growth fills formatted cells, keeps pasted formats, skips arrays
From the second CodeRabbit review of #259 and a review of the new row:
- Paste Special: notes, column widths, and unlinked formats or validation
  write no entry, so they don't grow a table; a linked paste does.
- An empty cell of the new row that was formatted already still takes the
  calculated column's formula, and keeps its format.
- Every entry in the new row (not only the cell that started the growth)
  takes the column's format when its own style is at most a number format;
  formatting pasted with it stays.
- A table doesn't grow over a multi-cell legacy array, which insert.table
  refuses inside a table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:21:18 -03:00
Harrison Booth 1e3fc9ee37 XLSX: keep a legacy modify password on save when the workbook has no user name 2026-10-26 06:52:05 -05:00
AlissonFAandClaude Opus 5.5 07600d3523 #258: table growth skips format-only commands and protected sheets, keeps the array check
From the CodeRabbit review of #259:
- Format Painter and Paste Special > Formats touch the cells they format; a
  filled cell below a table no longer pulls it in (Ctx::formats_only).
- On a protected sheet a table doesn't grow, as in Excel: the expansion wrote
  formulas into locked cells of the new row and the whole edit was refused.
- Growth asks for a full recalculation (Ctx::full_recalc) instead of marking
  the edit structural, so editing part of a legacy array below a table is
  still refused.
- Doc comment for auto_expand_tables; parity doc says tables don't grow
  below a totals row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:48:52 -03:00
AlissonFAandClaude Opus 5.5 b4feff7be2 #258: name new table columns like Excel; leave header-less tables' first row alone
- A column added by typing to the right of a table takes the lowest free
  `ColumnN` (from Column1), as Excel does, instead of Column{n+1}, which could
  repeat an existing name.
- A typed header that repeats a column name is made unique (`a` -> `a2`).
- A table without a header row keeps the generated name on the column only:
  no name is written into its first data row, and a value typed there stays
  a value.
- Tests for both, and for content already beside and below a table:
  formatting it leaves the table alone, retyping it takes it in, as observed
  in Excel (issue #258 comment).
- docs/target-app-parity.md: tables row and revision history.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:21:52 -03:00
AlissonFAandClaude Opus 5.5 2051a15c30 #258: drop the unrelated CRLF change in xtask parity and keytips
Review asked for it to go in its own PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:55:29 -03:00
AlissonFA e3f6c66a6a Merge origin/main into feat/table-auto-expansion
# Conflicts:
#	crates/engine/src/cmd/edit.rs
2026-10-26 07:55:24 -03:00
ZaxaerithandCodex de8f36ee33 fix(ui): left-align font name in Home ribbon (#2454)
Co-Authored-By: Codex <[email protected]>
2026-10-26 18:45:52 +08:00
dotCooCoo 06c2b1440b Fill handle: Linear Trend and Growth Trend on the right-drag menu for numbers
When every source cell holds a number, the right-drag fill menu now
also offers Linear Trend and Growth Trend. edit.autoFill takes them as
the modes linearTrend and growthTrend.

Linear Trend continues the least-squares line through each row or
column of the source, and Growth Trend continues the exponential curve
fitted to it, as the TREND and GROWTH functions fit them for positive
numbers: 1, 2 continues as 3, 4, 5 or as 4, 8, 16. Dragging up or left
continues the trend backward. The source keeps its values, and a lone
number repeats. Growth Trend is offered only when each row or column is
all above zero or all below zero; numbers below zero grow away from
zero.
2026-10-25 21:57:45 -07:00
Harrison Booth f7380202fe Merge remote-tracking branch 'origin/main' into gc-mg-2508r
# Conflicts:
#	crates/model/src/workbook.rs
2026-10-25 23:42:55 -05:00
Harrison Booth 4fa40fb932 Merge remote-tracking branch 'origin/main' into gc-mg-2508r 2026-10-25 23:07:26 -05:00
zyzabruh a53483874e Formula: document transpose_ref's turn and its #REF! contract (review #2606)
CodeRabbit's only finding on the pull request was docstring coverage on the
touched functions; this is the one that carried an undocumented contract —
`None` means an end left the sheet and the caller turns it into `#REF!`.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-10-26 01:40:53 +01:00
zyzabruh dd136062f5 Paste Special: a transposed paste turns formula references as Excel does (fixes #2450)
Paste Special > Transpose moved the copied cells but adjusted every formula
with `shift_relative`, the adjustment of an ordinary copy, so the formula kept
the offset it had in the source: `=A3+1` copied from A3:A4 and pasted at C3
read the cell above instead of the cell to its left and showed 1/1/1900.

Excel turns the references instead. Observed against Excel 16 on synthetic
workbooks (relative, `$B$1`, `B$1`, `$B1`, ranges, another sheet, whole rows
and columns, a reference off the grid, a source block not starting at A1, and
a 2x2 block): the row offset of a reference becomes its column offset and the
other way round around the pair of positions of the cell carrying the formula,
`(r, c)` -> `dest + (c - src.col, r - src.row)`. A reference pinned with `$`
is left exactly as written, a whole-row or whole-column reference comes back
as a cell range whose open side runs from the transposed far edge of the
sheet to its end (`1:2` -> `F$6:G$1048576`), and a result outside the grid is
`#REF!`.

`adjust::transpose_relative(e, src, dest)` implements that beside
`shift_relative`, and `paste_special` uses it when `transpose` is set; the
paste-link and cut-paste paths are untouched.

Tests: `tests::copy_transpose` in gridcraft-formula covers the observed cases
including the two shapes above and `#REF!`; `transposed_paste_turns_the_formula_with_the_cell_that_carries_it`
replays the issue's steps and checks the value is the day after the cell to
the left, `transposed_paste_turns_every_kind_of_reference_the_way_excel_does`
covers a relative, a pinned, a ranged and a whole-column reference end to end.

Docs: docs/ui-parity.md (header and revision history), ROADMAP.md (header and
progress log).

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-10-26 01:27:52 +01:00
Harrison Booth 6f63c784bc Merge remote-tracking branch 'upstream/main' into gc-mg-2508b
# Conflicts:
#	Cargo.lock
2026-10-25 18:11:51 -05:00
vangel76andClaude Sonnet 5.5 a98f290ec0 Quick Analysis: use Id::unique for the area ids (Id::new is deprecated upstream)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 00:06:42 +01:00
dotCooCoo d5b23a5e79 Charts: 100% Stacked Line, with or without markers, draws values as shares of each category's total
Insert > Line or Area and the All Charts list offer 100% Stacked Line
and 100% Stacked Line with Markers, and insert.chart and chart.set take
them as type line with subtype stacked100 or stacked100Markers. Each
series' line is drawn at the running sum of its share of the category's
total and the shares before it, so when no value is negative, the last
series reaches the top in every category with a nonzero total. When
every series on the value
axis is 100% stacked and no value is negative, the axis runs from 0% to
100%. The with-markers kind draws a marker at each point.

An XLSX line chart with percentStacked grouping now opens as 100%
stacked, with markers unless every series has the marker symbol none or
the group turns markers off, and is saved back as percentStacked. It
used to open as a stacked line and was saved as stacked. A 100% stacked
line series in a combo chart is still saved as a standard line.
2026-10-25 16:04:44 -07:00
vangel76andClaude Sonnet 5.5 870e2658ae Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 00:03:24 +01:00
alosslessdev 18f11876e3 Tests: restore the data validation dialog test the rebase dropped (#1822) 2026-10-25 17:45:30 -05:00
Neil Cawse 80b8786969 Merge main (ad10881) into the branch 2026-10-25 22:21:38 +00:00
Neil Cawse d0ad5ba6dc Merge main (ad10881) into the branch 2026-10-25 22:02:37 +00:00
alosslessdev a5b1415c9e Conditional formatting: translate the rule editor's Edit and More Rules labels (#1822) 2026-10-25 16:10:03 -05:00
Harrison Booth ce64da3286 XLSX password to modify: compare the reserved file by identity on Save; keep a legacy hash only beside a userName (#2508) 2026-10-25 15:35:28 -05:00
Harrison Booth 87f9c4b12d Merge remote-tracking branch 'upstream/main' into gc-mg-2395q
# Conflicts:
#	ROADMAP.md
#	crates/ui-egui/src/tabs.rs
#	docs/ui-parity.md
2026-10-25 15:31:18 -05:00
Harrison Booth ceca4b151e Merge upstream main into the XIRR branch
Keeps main's newer doc rows (Maximum Iterations, the 10-16 and 10-17 entries) alongside the XIRR and blank-cash-flow entries. Code auto-merged; only ROADMAP.md and docs/function-parity.md conflicted.
2026-10-25 15:24:47 -05:00
Harrison Booth 70fb318377 Merge upstream/main into gc-pivot-data-model-caches 2026-10-25 15:23:25 -05:00
Harrison Booth 14c81bfdd6 XLSX password to modify: merge upstream main, resolve Cargo.lock and ROADMAP conflicts (#2508) 2026-10-25 15:23:16 -05:00
alosslessdev 5a035ac5c6 Conditional formatting: keep the opening scope for colour scales and reject bad rule params (#1822) 2026-10-25 14:26:54 -05:00
alosslessdev 81a8abc12b New Formatting Rule: pick grid references for formula rules and keep the opening range (#1822) 2026-10-25 14:26:54 -05:00
alosslessdev 8b17f1e779 Conditional formatting: rustfmt after the rebase (#1822) 2026-10-25 14:26:54 -05:00
alosslessdev 6cfd7d83aa Contributors: add alosslessdev (#1822) 2026-10-25 14:26:54 -05:00
alosslessdev a327501fb1 Conditional formatting: cover the new rule labels in the remaining catalogs (#1822) 2026-10-25 14:26:53 -05:00
alosslessdev 516b19c151 Conditional formatting: require a formula for formula scale stops (#1822) 2026-10-25 14:26:41 -05:00
alosslessdev fded60a325 Conditional formatting: refuse non-numeric colour-scale stop values (#1822) 2026-10-25 14:26:41 -05:00
alosslessdev c693db2b9f Conditional formatting: colour-scale editor and New Rule list (part of #1165)
New Formatting Rule offers Excel's six rule types. The colour-scale branch
edits per-stop type, value and colour, and Manage Rules edits a rule in place.

Formula rules refuse an empty or unparseable formula: the dialog keeps OK
disabled until a formula is typed, and the command rejects both an empty rule
and a formula that does not parse (#1999), so neither a rule that never applies
nor a workbook Excel cannot open is written.

Percent and percentile stops are clamped to 0-100, and an edit past the last
rule names home.manageRules and leaves no undo step.
2026-10-25 14:26:41 -05:00
vangel76andClaude Sonnet 5.5 a2caeedcd9 Quick Analysis: use theme category colours after the theme change on main
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 10:26:14 +01:00
vangel76andClaude Sonnet 5.5 2a10509d65 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 10:25:05 +01:00
Harrison Booth 38fa0dc050 XLSX password to modify: address review comments
- A read-only open refuses Save to the file it came from; Save As to
  another file still works, so the reservation holds.
- Verify SHA-1 password-to-modify hashes, as XLSX fileSharing allows.
- An encrypted and reserved workbook asks for the password to modify
  after its decryption password, keeping the decryption password.
2026-10-24 18:02:07 -05:00
Harrison Booth ae50127952 XLSX password to modify: fix dialog return type and test's Arc workbook edit 2026-10-24 17:44:33 -05:00
Harrison Booth 95c0800c22 XLSX: password to modify (#921): kept on save, asked for on open or open read-only 2026-10-24 17:40:24 -05:00
Harrison Booth 707ce9e14c Resize Table: name formula headers by value and clear pictures under normalized headers
A formula header with formulas shown was named by its source text, so the
header became constant text like "=1+1". Use the value text instead.

Header normalization wrote through cells.set, which left a picture at that
address in place. Use Sheet::set_cell so the picture is removed with it.
2026-10-24 17:26:54 -05:00
Harrison Booth b97c27f2b3 Test: the repro helper tolerates refused steps again, with the reason in a comment 2026-10-24 17:10:53 -05:00
Harrison Booth 2d65676f5d Filter: bound a table-header filter by the table, refuse a narrower range that would drop criteria, fail the test helper on errors 2026-10-24 17:04:44 -05:00
Harrison Booth 79324b6c17 Resize Table test: the PivotTable fixture anchors outside the resize range
The filter report starts above its anchor and overlaps the resize range, so the test
checks the report's extent rather than only the anchor cell.
2026-10-24 17:03:49 -05:00
Harrison Booth d2506c03d9 Resize Table: a normalized header keeps the settings of its own column
With a header row, a resized column found its settings by name. A blank header that
took a generated name could pick up the settings of another column with that name.
A header that was normalized now keeps the column at its address.
2026-10-24 16:56:45 -05:00
Harrison Booth 214ad97372 Test: a partial sheet filter folds into the table column it filters 2026-10-24 16:55:24 -05:00
Harrison Booth 46bdd416bb Test: pass the trust level to DocState::new in the subtotal filter test 2026-10-24 16:48:11 -05:00
Harrison Booth 3d923f3b30 Resize Table: refuse merged cells, PivotTables and arrays; name new columns like Excel
Merges the fork's table.resize work into the task branch. Main already refuses a
resize that lands on another table; this adds the rest of what Excel refuses:
a merged area, a PivotTable report, and a multi-cell array formula. A spilled
formula is still allowed, as in Excel.

Columns a resize adds are now named the way Excel names them: an empty header
continues a ColumnN on its left, otherwise it takes the lowest free ColumnN, and
a repeated header gets the next free suffix. Previously a generated name could
repeat one already in the header row, so the header and the column names drifted
apart and the reader renamed the column on reopen. Generated names are written
into the header row as text. A table without a header row keeps its names by
position.
2026-10-24 16:46:40 -05:00
Harrison Booth 937634a31a Test: drop internal tracker id from subtotal filter test header 2026-10-24 16:38:52 -05:00
Harrison Booth d07795efae Merge origin/main into gc-sort-exact-number-order
# Conflicts:
#	ROADMAP.md
#	crates/calc/src/tests.rs
#	docs/function-parity.md
2026-10-24 16:38:37 -05:00
Harrison Booth 591b97aede Merge remote-tracking branch 'origin/fix/subtotal-filtered-rows-roundtrip' into gc-subtotal-filtered-rows-roundtrip
# Conflicts:
#	crates/engine/src/cmd/data.rs
2026-10-24 16:38:31 -05:00
Harrison Booth c506178922 Calc: check =ROWS(C4#) on a one-value table result 2026-10-24 16:37:43 -05:00
Harrison Booth a6b73d11e9 Merge origin/main into gc-fb-2490 2026-10-24 16:37:34 -05:00
Harrison Booth 5e0fe2d28d XIRR: use the first nonzero cash flow for the search direction and residual
A leading zero cash flow made the residual zero and the search direction
wrong, so XIRR returned #NUM! for series a zero adds nothing to.
2026-10-24 15:57:26 -05:00
Harrison Booth fb38290e45 Merge fix/xirr-blank-cash-flows: XIRR counts a blank cash flow as 0 alongside Excel's solvers 2026-10-24 15:44:22 -05:00
Harrison Booth b107dedf7e Merge origin/main into gc-fb-2398-xirr 2026-10-24 15:44:04 -05:00
Harrison Booth 9b7c5ca1f6 Keyboard: Add mode drops only its own provisional area; selection commands go through app.run 2026-10-24 15:41:13 -05:00
Harrison Booth ec77c810f8 XLSX: report sheet extensions with unmodelled children as dropped; consolidate xlsx parity rows 2026-10-24 15:35:54 -05:00
Harrison Booth 8471ccace5 Keyboard: Add mode keeps areas for Home and End; a click inside a larger area removes it 2026-10-24 15:33:04 -05:00
Harrison Booth bf9531954d Keyboard: test that an Add-mode header drag keeps the earlier areas 2026-10-24 15:25:47 -05:00
Harrison Booth 41a1a3f8bc Keyboard: Add-mode Shift-click keeps earlier areas; Dutch status labels 2026-10-24 15:21:08 -05:00
Harrison Booth 10c023754e XLSX: keep PivotTables on a data connection, the Data Model or another workbook on save
PivotTables whose cache source is a data connection, the workbook's Data Model, or a range in another workbook were read as unsupported and dropped with their caches on save. They are now kept by the pass-through layer: table, cache and records parts unchanged, the Data Model part (xl/model/item.data) byte for byte whenever its connections are kept. A cache is kept only with its connections or the model; otherwise the PivotTable is left as plain cells with one warning.
2026-10-24 15:16:08 -05:00
Harrison Booth fa17a79cba Merge remote-tracking branch 'origin/main' into gc-f8-extend-add-selection
# Conflicts:
#	ROADMAP.md
#	docs/ui-parity.md
2026-10-24 15:15:58 -05:00
Harrison Booth 154273a7d8 Merge remote-tracking branch 'origin/main' into gc-extlst-passthrough
# Conflicts:
#	ROADMAP.md
2026-10-24 15:12:34 -05:00
vangel76andClaude Opus 5.5 2a59d7f15d Quick Analysis: keep clear of the Auto Fill Options button, tests in the shared binary
After a fill-handle drag both buttons sat at the selection's corner and
the Quick Analysis one, painted on top, took the click. The Quick
Analysis button now waits until the fill is no longer current; Ctrl+Q
still opens the popup. Drops "Bar" from the Japanese EXTRA list, now a
DIALOGS key, and moves the button tests into tests/it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-24 20:10:10 +02:00
vangel76andClaude Opus 5.5 818c97a632 Merge upstream/main into feat/quick-analysis-791
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-24 19:59:19 +02:00
DerKarussellbremserandClaude Opus 5.5 c4ef580a22 Grid: imitate the styles of the face actually drawn; bold for shrunk and rotated text
Review fixes. The slant and bold markers are now set from the face the role
is drawn in (the first whose file could be read), so a family whose bold
or italic file is missing gets them imitated too, and a later binding that
no longer needs a marker removes it. The bold offset follows the size that
is painted after Shrink to Fit, and rotated text gets its second
impression along its own direction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KKbbMZpkzQuncTpqAyhkp9
2026-10-24 14:41:41 +02:00
DerKarussellbremserandClaude Opus 5.5 17aae2da04 Grid: italic and bold in a one-face font are slanted and thickened, as in Excel
Arial Black has a single face. A cell in Arial Black, bold italic, drew it
upright and at its own weight; Excel slants it and thickens it (observed in
its PDF: oblique by 1/3, outlined 0.23 pt at 9 pt). fonts.rs notes, while it
binds a family's roles, which italic roles got an upright face and which
bold roles got the plain face; the grid then lays such text out with egui's
italics and paints it a second time about 1/36 of its size to the right.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KKbbMZpkzQuncTpqAyhkp9
2026-10-24 14:24:30 +02:00
Harrison Booth aea9a02bce Calc: a one-value dynamic-array result in a table is not #SPILL! 2026-10-23 17:10:23 -05:00
Harrison Booth a4309846b2 Keyboard: Add-mode header drags keep earlier areas; Shift-click ends a pending area 2026-10-23 16:58:55 -05:00
Harrison Booth fd6d6cee88 Merge origin/main into gc-extlst-passthrough
# Conflicts:
#	ROADMAP.md
#	docs/file-format-parity.md
2026-10-23 16:56:16 -05:00
Harrison Booth 852b1a4bfb Merge remote-tracking branch 'origin/main' into gc-irr-xirr-excel-solver
# Conflicts:
#	ROADMAP.md
#	docs/function-parity.md
2026-10-23 16:55:49 -05:00
Harrison Booth a6bedd5153 Docs: keep the UI parity revision table well-formed 2026-10-23 16:41:40 -05:00
Harrison Booth 3aa8727fd6 Merge remote-tracking branch 'origin/main' into gc-array-entry-marks-all-cells
# Conflicts:
#	crates/engine/src/cmd/edit.rs
2026-10-23 16:33:15 -05:00
Harrison Booth 1d0360153f Merge the F8 and Shift+F8 selection-mode branch 2026-10-23 16:29:07 -05:00
Marco Arnulfo df2b24dbfd Print Selection: split a multi-area range at its commas before dropping each Sheet! qualifier, so earlier unqualified areas are kept 2026-10-23 19:12:21 +02:00
MarekSpodBiedry 8513c584cb Print text that overflows out of the last used column in PDF export (#2333) 2026-10-23 17:36:02 +02:00
Marco Arnulfo db2fffa9be Print: Print Selection in File > Print > Settings, several selected areas print one after the other (fixes #2351) 2026-10-23 17:25:24 +02:00
AZIS LAMAYUDA 7e4f2c4a0d Merge branch 'main' into fix/linux-titlebar-adwaita 2026-10-23 22:21:11 +07:00
MarekSpodBiedry 1da552fc9f Wayland: track synthetic wheel events when ending a stuck Ctrl wheel touch (#2213) 2026-10-23 16:08:20 +02:00
Marco Arnulfo 42ad67ab13 Keep the zoom per step when undoing or redoing several steps
edit.undo and edit.redo with `steps` > 1 ran keep_zoom once, comparing the
first and last snapshots. Adding C and deleting B leaves the same sheet count
under other names, which keep_zoom took for a rename of B to C, so C's zoom
landed on B. keep_zoom now runs after each restored snapshot, against the one
it replaces.
2026-10-23 15:23:03 +02:00
Marco Arnulfo b21dd9151f Keep the zoom when undoing or redoing a sheet rename
keep_zoom matched sheets by name, so undoing a rename found no match and
brought back the zoom from before the rename. A sheet missing by name now
falls back to the one at the same index, when the sheet count is unchanged
and that sheet's name isn't in the restored snapshot.
2026-10-23 10:18:20 +02:00
kezmdorandClaude Opus 5.5 b9324d9179 Formula entry: text that would read as a formula is edited with its apostrophe
`text_needs_quote_prefix` still used the old rule (a sign followed by a
letter or `(`), so text such as `+5+4` (typed as `'+5+4`, or read from a
CSV or XLSX) was edited without its apostrophe and became a formula when
confirmed unchanged. It now asks what `input_to_cell` asks: the entry
starts a formula and parses as one. Text that stays text anyway (`--`) is
still edited as it is. Found by @iluebbe in #2023.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 09:13:27 +02:00
Marco Arnulfo edd64e9afc View: zooming is not an undo step (fixes #2313) 2026-10-23 02:43:40 +02:00
Vedran DobosandClaude Opus 5.5 81e523e431 AutoFit: a table's header is measured in the table style's bold font
AutoFit Column Width measured every cell in its own style, but the grid draws a table's cells in the
table style, which makes the header row bold, so a bold heading could be fitted too narrow. AutoFit
now measures a table cell in the font the table gives it. (Found by CodeRabbit on #2269.)

The table-filter AutoFit test checked the fitted column against the engine's text estimate, while
AutoFit measures with the font the grid draws (#1316); where that font is installed the estimate is
wider, so the test failed off Linux. It now measures the heading as the grid draws it, in the table
style's font.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 00:24:07 +02:00
Vedran DobosandClaude Opus 5.5 60c758af66 CSV: keep a sep= delimiter only if it would be detected again; a first row like a sep= line stays data (#1446)
Review of #2270. A delimiter a sep= line named was kept for saving whenever it was , ; or tab, but
the saved file has no sep= line, so sep=; over a;b,c reopened split at the commas. It's kept now only
when detection would pick it again; otherwise the file is saved with commas. A sheet whose first row
reads as a sep= line (a lone sep=; in A1) was saved bare and that row was dropped on reopening; it's
now written behind a sep= line naming the delimiter. Excel writes such a row bare and reopens the
file garbled (observed: Excel 16.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 23:39:58 +02:00
Vedran DobosandClaude Opus 5.5 6ce1ce9c6d Format: widening looks at the target's stored cells and spills, and indexes its merges (#1077)
Review of #2271. A target over 4,000,000 positions was skipped whole, so whole columns with a number
a million rows down didn't widen: the stored cells looked at are capped instead (1,000,000). Spilled
numbers are measured as the grid shows them; before, a spill child's empty stored cell hid its
number. Merged areas are checked through per-column row intervals built once per command, not a scan
of every merge for every number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 23:27:09 +02:00
Harrison BoothandClaude Sonnet 5.5 9b594efc67 Merge main into fix/xirr-blank-cash-flows
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-22 15:39:34 -05:00
MarekSpodBiedry db2ff17229 Wayland: wheel without Ctrl scrolls again after a Ctrl+wheel zoom (#2213) 2026-10-22 21:09:14 +02:00
vangel76 2681d7b6df Merge upstream/main into feat/quick-analysis-791 2026-10-22 19:45:19 +02:00
Vedran DobosandClaude Opus 5.5 f30c206a05 Format: Format Cells' number formats widen columns too, as in Excel (#1077)
Observed in Excel 16.0: a number format applied to a number widens a column not sized by hand,
whether it comes from the ribbon or the NumberFormat property (as Format Cells sets it); a value
entered into an already formatted cell doesn't. shrink_to_fit's #### case now sets its column's
width by hand, as Excel would otherwise widen it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 15:20:40 +02:00
Neil Cawse 3d82a9cf4e Clarify chart cache budget drops 2026-10-22 06:30:27 +00:00
Neil Cawse 5b8c2cde8d Bound total chart cache imports 2026-10-22 06:23:54 +00:00
Neil Cawse 78cf72ae0f Preserve chart cache tails and series 2026-10-22 06:16:22 +00:00
Neil Cawse 0a659997ee Adjust Values row round-trip test 2026-10-22 06:14:54 +00:00
Neil Cawse a6870d0e3f Preserve Values row setting on round trip 2026-10-22 06:13:58 +00:00
Neil Cawse 38696b93a4 Bound chart import expansion 2026-10-22 06:11:32 +00:00
Vedran DobosandClaude Opus 5.5 744c6cde44 Tests: the table-filter AutoFit test measures the heading with the grid's font
`table_filter_autofit_works_through_command_and_header_double_click` checked the fitted column
against the engine's text estimate, but AutoFit measures with the font the grid draws (#1316).
Where that font is installed (seen on Windows 11) it is narrower than the estimate, so the test failed
there at 50% zoom; on Linux CI the font is missing and both fall back to the estimate. The test now
measures the heading the way AutoFit and the grid do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 07:51:58 +02:00
Neil Cawse 8338a35da6 Keep main's chart revision row text 2026-10-22 05:41:58 +00:00
Vedran DobosandClaude Opus 5.5 4e85a1fd21 CSV: an Excel sep= first line names the delimiter (#1446)
File › Open read a `sep=|` first line as data and split the file by the detected delimiter, so a
`|` file stayed one column. When the delimiter is detected, a first line `sep=` plus one character
now names it and isn't data, as observed in Excel 16.0: spaces ignored, any case, the line may be
quoted; `sep=` alone (or a non-ASCII character) splits nothing; two characters or the line anywhere
but first is data; `sep="` splits at the quotes. A given delimiter wins. Saved again, the file keeps
`,` `;` or tab; any other named delimiter is written as commas, so it reopens in the same columns.

parse_records takes an optional delimiter and quote character for the two cases that split or
quote nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 07:38:28 +02:00
kezmdorandClaude Opus 5.5 d51a6de104 Merge upstream main into fix/1834-autosum-edit-mode
Conflicts: AutoSum's and Recommended Charts' menu-style cases in
`run_or_alert` were both added after Export as PDF (kept both);
docs/ui-parity.md keeps main's rows with this change added, and main's
two Point mode rows are one again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 07:26:16 +02:00
kezmdorandClaude Opus 5.5 9424a96d9b Merge upstream main into fix/2023-plus-minus-starts-formula
Conflicts: `starts_formula` and main's `number_stored_as_text` were both
added after `parse_number_text_in` (kept both); formula_locale's test
modules are combined; docs/ui-parity.md keeps main's rows with this
change added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 07:25:19 +02:00
Neil Cawse 4f92fc417b Fix chart parity chart type notes 2026-10-22 05:23:40 +00:00
Vedran DobosandClaude Opus 5.5 f3a7c72bb6 Format: number formats widen columns that weren't sized by hand (#1077)
Increase/Decrease Decimal and the ribbon's other number formats widened the format but never the
column, so the number turned into ####. A column nobody sized by hand now widens to the widest
number in the target, as observed in Excel 16.0: AutoFit counts as automatic, Column Width (or
dragging the border) as by hand; hidden columns, text, General numbers, merged and shrink-to-fit
cells don't widen; columns never narrow.

LineInfo::custom now marks columns set by hand too. XLSX reads and writes it as Excel does
(customWidth without bestFit = by hand; automatic widths get bestFit and customWidth), and .xls
reads COLINFO's fUserSet and fBestFit the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 07:21:26 +02:00
Neil Cawse b56c2ddc7e Fix PivotChart innermost category labels 2026-10-22 05:20:59 +00:00
Neil Cawse 12c08d7e9d Fix hidden Values row with page filters 2026-10-22 05:19:41 +00:00
Neil Cawse 7bce227ed6 Merge main (06920de) into the branch 2026-10-22 05:15:04 +00:00
Neil Cawse 32b2bbe471 Fix PivotTable page header location 2026-10-22 05:11:53 +00:00
Neil Cawse 2b297cd194 Fix hidden PivotTable header location 2026-10-22 05:11:10 +00:00
Neil Cawse 727c727ff5 Merge main (06920de) into the branch 2026-10-22 05:10:50 +00:00
kezmdorandClaude Opus 5.5 1f6adbe382 Merge upstream main (0.9.0) into fix/1834-autosum-edit-mode
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 09:20:08 +02:00
kezmdorandClaude Opus 5.5 c29f282712 Merge upstream main (0.9.0) into fix/2023-plus-minus-starts-formula
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 09:11:12 +02:00
AZIS LAMAYUDA 76433d99a6 Merge branch 'main' into fix/linux-titlebar-adwaita 2026-10-21 06:03:09 +07:00
Harrison BoothandClaude Sonnet 5.5 c0ae95f721 XIRR counts a blank cash flow as 0; XNPV errors like Excel for blanks
A cash-flow column with unused (blank) rows made XIRR return #VALUE!
where Excel returns the rate. Behaviour observed in Excel on synthetic
workbooks: XIRR treats a blank value as 0 and ignores a blank date next
to a blank or 0 flow (a nonzero flow without a date is #NUM!). XNPV is
strict: a blank value is #NUM!, and so is a blank date next to a blank or
0 value (#VALUE! next to a nonzero one).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-20 09:14:03 -05:00
kezmdorandClaude Opus 5.5 601cc60cfc AutoSum: a range that isn't text counts as no range, as in the engine
`formulas.autoSum` reads `range` with `str_param`, so `{"range": null}`
means the selection; the UI's check for the editor proposal now reads it
the same way (CodeRabbit review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 09:18:33 +02:00
kezmdorandClaude Opus 5.5 132bd4e9a8 AutoSum: test the menu functions; keep the new editor method clear of #1056
Home › AutoSum ▾ Average proposes `=AVERAGE(range)` the same way (and so
will Formulas › AutoSum once it has the menu, #658). `point_last_argument`
moves to the end of `impl EditState`, so this PR no longer touches the
lines #1056 and #1838 change after `insert_ref`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 08:59:30 +02:00
kezmdorandClaude Opus 5.5 fdad356fd2 AutoSum on one cell proposes its range in the editor, like Excel (fixes #1834)
AutoSum from the ribbon or keyboard entered `=SUM(range)` at once, so the
range could only be changed by editing the formula afterwards. On one
cell it now runs with `enter: false` and leaves `=SUM(B2:B4)` in the
editor with `B2:B4` pointed and selected: a click, drag, arrow key or
typing replaces it, and Enter enters the formula. With nothing to sum
the caret waits between the parentheses of `=SUM()`. A block still gets
its totals at once, and programmatic `formulas.autoSum` (control
channel, CLI, MCP) is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 08:48:08 +02:00
kezmdor a8810d7a7a Stack on #1332: Alt+= no longer starts an edit with the = it types 2026-10-20 08:27:39 +02:00
kezmdorandClaude Opus 5.5 0c78ddf79f Formula entry: a + or - entry that isn't a valid formula stays text
Observed in Excel for the web: `--`, `-----`, `+5+` and `+49 170 1234567`
stay text, and `- item` is #NAME?. Only `=` entries are refused. Entry
now tries a `+`/`-` entry as `=` followed by the entry and, when that
doesn't parse, reads it as a number or text as before; the Spanish
formula path does the same with its parser.

Text to Columns no longer needs its own text fallback, so that change
is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 08:04:50 +02:00
kezmdorandClaude Opus 5.5 1af4d38e71 Formula entry: keep canonical's body binding, so the diff stays small
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 07:45:49 +02:00
kezmdorandClaude Opus 5.5 4215f07bb3 Formula entry: a leading + or - starts a formula, like Excel (fixes #2023)
Typing `+5+4` entered the text `+5+4`: a leading sign started a formula
only when a letter or `(` came next. Now any entry that starts with `+`
or `-` and isn't a number on its own is a formula, as in Excel, so
`+5+4` enters `=+5+4`. `+5`, `-5` and a lone sign are unchanged.

The rule lives in `gridcraft_core::parse::starts_formula`, shared by the
engine's entry and the Spanish formula-locale path in the UI, where a
signed decimal-comma number (`-1,5`) stays a number. Text to Columns
keeps a part that isn't a valid formula as text instead of emptying
its cell, as paste and Replace already do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 07:24:25 +02:00
Neil Cawse 9f127b5b80 Merge main (23829d8) into the branch
# Conflicts:
#	crates/engine/src/tests.rs
2026-10-20 01:46:28 +00:00
vangel76andClaude Sonnet 5.5 480b8a88b5 Quick Analysis: report calling command in block errors, clip tile labels
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-20 01:35:21 +02:00
vangel76 b82c4fbd30 PR795: merge main and retain Quick Analysis and context menu translations 2026-10-20 00:55:55 +02:00
AZIS LAMAYUDA b2a2e74316 #54: use font-free Adwaita decorations on Linux and FreeBSD 2026-10-19 06:01:15 +07:00
Neil Cawse 6421731f9a PivotTables: the Values caption heads the Σ Values column
With values on rows in Outline or Tabular, the Σ Values column header showed
"Values" even when the file sets dataCaption; Excel shows the caption.
2026-10-18 19:36:37 +00:00
Neil Cawse df97bf8445 PivotTables: leave the grand-total mapping to #1882
The rowGrandTotals/colGrandTotals fix moved to its own PR at review's request.
2026-10-18 19:16:42 +00:00
AZIS LAMAYUDA b321e50197 #54: limit Wayland title bar fix to Adwaita decorations 2026-10-18 21:32:46 +07:00
AZIS LAMAYUDA c2362ccff5 #54: fix Linux Wayland title bar and Clippy warnings
Enable winit's Adwaita window decorations on Linux Wayland instead of the minimal fallback frame, improving the appearance of minimize, maximize, and close buttons.

Keep the native Linux window title as "GridCraft". The ribbon continues to display the document name and edited marker, avoiding duplicate "Book1" titles.

Update Cargo.lock and UI documentation.

Fix two existing Clippy warnings without changing behavior:
- Move the XLS format-count condition into a match guard.
- Simplify the assertion checking that a preserved VML drawing is absent.

Validation:
- All 8 cargo xtask ci checks passed: fmt, clippy, tests, assets, layers, wasm, parity, and keytips.
- 1,617 tests passed, 0 failed, and 1 ignored.
- Verified window appearance on Ubuntu 26.04.1 LTS with Wayland.
- Tested application launch, resize, normal shutdown, and local AppImage launch.

Refs #54.
2026-10-18 10:05:38 +07:00
Sebastian Whincop 826ba30f5e Merge branch 'storytold:main' into fix/excel-snap-to-zero 2026-10-16 21:04:08 +13:00
Harrison BoothandClaude Opus 5.5 cdb3c163ec ft-3ir.2.1: keep PivotTables on a data connection or the Data Model on XLSX save
A PivotTable whose cache has cacheSource type="external" (a data
connection, or the workbook's Data Model: OLAP caches with saveData="0"
and no records) was read as unsupported and dropped on save with its
cache, and the Data Model part (xl/model/item.data) was never kept.

Such PivotTables are now reported by read_pivots and kept by the
pass-through layer like those on another workbook: table, cache and
records parts unchanged, original cacheId, style ids renumbered. The
connection is looked up in xl/connections.xml to tell the Data Model
from a plain connection. The Data Model part is kept byte for byte
whenever the workbook's connections are kept. A cache on a connection is
kept only with the connections, one on the model only with the model;
otherwise its PivotTable is left as plain cells with one warning.

Checked in Excel with synthetic workbooks: Excel needs the table, cache,
connections.xml and the hidden _xlcn. name of a worksheet connection to
open the file, and item.data to refresh it; the x15:dataModel workbook
extension is not needed and is not kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 06:27:02 -05:00
Harrison BoothandClaude Opus 5.5 5a72aff0c5 Resize Table: refuse another table, merged cells, a PivotTable or an array; keep header names in step
table.resize grew a table over a neighbouring table without checking, leaving two
overlapping tables that Excel refuses to open as is. It now refuses, as Excel does, a
new range that takes in another table, a merged area, a PivotTable report or a
multi-cell array formula. A spilled formula is still allowed (Excel allows it too).

The columns a resize added were named by position ("Column{i+1}"), which could repeat
a name already in the header row (a table whose third column is Column3, resized to
start there, got a second Column3). The header row and the column names then drifted
apart and the reader made the name unique on reopen ("Column32"). New columns are now
named the way Excel names them (observed): an empty header continues a ColumnN on its
left, otherwise takes the lowest free ColumnN, and a repeated header gets the next free
suffix. The names are written into the header row as text. A table without a header
row keeps its column names by position.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 05:08:00 -05:00
Harrison BoothandClaude Opus 5.5 43ccb39ba3 Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection
F8 toggles Extend Selection: arrows, Page Up/Down, Ctrl+arrows, Home and
Ctrl+Home/End extend from the anchor as if Shift were held, and a click
extends like Shift+click. Shift+F8 toggles Add or Remove Selection: arrows
move the active cell and keep the selected areas, Shift+arrows grow a new
area from there, and a click adds an area or removes a selected one, like
Ctrl+click. The status bar names the mode (translated in every catalog).
The key again, Esc or editing a cell ends it. UI-only command
ui.selectionMode sets or reports the mode for agents.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 04:26:44 -05:00
Harrison BoothandClaude Opus 5.5 e24a8631b4 Filter: SUBTOTAL over filtered table rows keeps its value after save and reopen
A sheet AutoFilter that overlaps a table can't be saved (the file only holds a
table's own filter there), so the writer dropped it. Its criteria were lost and
the rows it hid reopened as rows hidden by hand, which SUBTOTAL 1-11 counts.

- Save a sheet AutoFilter that starts on a table's header row as that table's
  filter (columns mapped to the table), merged with the table's own criteria.
- Filtering inside a table takes over the criteria the table already had, so a
  reopened filtered table filtered again saves both.
- From a cell outside a table, the filter range keeps off the table like Excel
  (observed: table B4:C8, AutoFilter from A1 covers A1:A3, from A6 A5:A8, from
  B3 A1:B3); an explicit range over part of a table is refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:59:25 -05:00
Harrison BoothandClaude Opus 5.5 df34dac2d1 Recalc: array-entering over a selection updates readers of the cells it clears
cell.set with array:true over a multi-cell selection cleared the other
cells of the range but marked only the first cell changed, so formulas
reading the cleared cells kept stale values until a full recalc (array
formulas hid this because their results refresh the range; a constant
input didn't). The clearing loop also stopped after a million addresses,
so a whole-column array left content further down in place.

The array branch now walks the cells the sheet holds in the range and
marks each one it clears. Clear (Delete and the Clear commands) had the
same cap on the addresses it marked: readers of cells past the first
million of a large range stayed stale. It now marks the cells it clears.

Found by the command-sequence fuzzer (seeds 4 and 1213).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 02:39:53 -05:00
Harrison BoothandClaude Opus 5.5 8d90b1ea03 fix(functions): XIRR and IRR follow Excel's solvers
XIRR returned the exact root (Newton with fallbacks and a bracketing
search), so it differed from Excel at about 1e-8 and converged where Excel
gives #NUM!. It now follows Excel's solver as reconstructed by observing
Excel with synthetic inputs: a sign-only search that brackets the root from
the guess (doubling; bisecting towards 0, halving towards 0 or stepping
halfway to -100% when the root is lower), then bisection with the midpoint
taken from the upper end, stopping when half the bracket is under
1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first value|, at most 100
XNPV evaluations. Dates before the first are allowed as in Excel; a guess at
or below -1 is #NUM!. Answers match Excel bit for bit in 888 of 910
synthetic cases with an answer; 97.7% agreement on 1,283 cases.

IRR now uses Newton on the discount factor 1/(1+rate), at most 100 steps,
stopping at a step under 1e-8, which agrees with Excel's #NUM! cases far
better (IRR of -100, 19 zeros, 1E-5 is #NUM!) and with its values to about
1e-12. A guess at or below -1 is #VALUE! like Excel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-15 00:07:34 -05:00
Harrison BoothandClaude Opus 5.5 921405fa02 SORT, SORTBY and Data > Sort order numbers exactly, like Excel
sort_compare compared numbers at 15 significant digits, so 0.3 and
=0.1+0.2 (0.30000000000000004) tied and kept their input order. Excel 365
orders them exactly in SORT, SORTBY, Data > Sort, the AutoFilter sort and
table sort: 0.3 first ascending, last descending, in either input order.
Numbers now compare with partial_cmp in sort_compare (0 and -0 still tie).
= and COUNTIF keep their 15-digit comparison; UNIQUE, RANK, LARGE, SMALL
and MODE were already exact, as observed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 21:18:25 -05:00
Harrison BoothandClaude Opus 5.5 f066fe994e XLSX: keep self-contained workbook and sheet extLst entries on save
Workbook extLst entries on an allowlist of single attribute-only elements
are kept in source order with calcFeatures: x15 and x14 workbookPr,
xlwcv:version and the Excel for Mac mx:ArchID. On sheets, the Excel for
Mac mx:PLV is kept and written after the extensions the sheet writer
emits, skipping any URI it already wrote. Entries are rebuilt from the
parsed element with the schema's attributes only. Extensions that point
at other content (slicers, timelines, data model, Google Sheets custom
data) stay dropped and are named in an open warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 19:43:43 -05:00
Harrison BoothandClaude Opus 5.5 8732325b58 ft-121.1.25: keep PivotTables whose source is in another workbook on XLSX save
A PivotTable whose cache's worksheetSource has an r:id to an
externalLinkPath relationship (range or defined name in another
workbook) was read as a model pivot with an unresolvable source, and the
writer then skipped it silently: the table, cache definition, records,
the cache's link and the workbook's pivotCache entry were all lost.

Such PivotTables are now reported by read_pivots instead of modelled and
kept by the pass-through layer: the table parts with their sheet, the
cache and records with the workbook and its original cacheId. Written
pivot caches skip the kept ids, a cache no kept table uses is dropped,
and the kept parts' dxfId and numFmtId references are renumbered to the
rewritten styles part (Excel refuses to open the file otherwise).
gridcraft-cli check counts kept PivotTables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 15:42:49 -05:00
Local contributor ec3666f913 PivotTables: collect General numbers only when the column has a date
date_cells hashed every non-date number of a column into the General set even
when no cell of the column was a date, which a numeric General row field paid
for on every refresh. The set is now built only when some flag is set.
2026-10-14 16:05:00 -04:00
Local contributor 20a85b2caf PivotTables: a General cell anywhere in the column makes its number a number
The General-wins rule ran in item interning, which only sees records that pass
the report filter, so filtering out the General cell made its number sort as a
date. The date flags are now decided over every record of the column before
filtering, as Excel's cache decides.
2026-10-14 14:57:40 -04:00
Local contributor 7fe89ba872 PivotTables: read date flags only for axis fields; General wins
Reading every source cell's style made each refresh of a large source much
slower. The source now keeps the sheet row of each record, and the per-cell
date flags are read only for ungrouped row and column fields, one format lookup
per distinct style.

One number in a date cell and in a General cell is one item; its sort class
depended on which cell came first. Any General occurrence now makes it a
number.
2026-10-14 13:23:52 -04:00
Local contributor 1ba5d323d0 XLSX: Multi-level PivotChart categories save as a multiLvlStrRef and still draw one label per point after a reopen
innermost_categories wasn't saved: the block was written as a 2-column strRef with an interleaved 8-point cache, so after save and reopen the chart drew 8 labels again. Flagged categories are now written as a multiLvlStrRef whose multiLvlStrCache has ptCount = the point count and one lvl of cell texts per level, innermost first, which a PivotChart reads back with the flag set. Categories without the flag are written as before.
2026-10-14 13:14:38 -04:00
Local contributor ef6776db8b XLSX: A matching multi-level PivotChart category block keeps its references and draws its innermost level
Since the previous commit, a multiLvlStrRef block of more than one level was always stale, so a save replaced Graph!$A$4:$B$7 with an innermost-only strLit and the name ref Graph!$C$3 with a literal, losing the outer level. The block is again compared by its innermost column (or row). When that holds the cache, the series stays live, its references kept and saved as before, and the new Series.innermost_categories flag makes the renderer draw only the innermost level, one label per point. A block whose innermost level doesn't hold the cache still plots its cache.
2026-10-14 12:45:59 -04:00
Local contributor 766b6d3a93 PivotTables: only date-formatted cells sort as dates
The date sort class came from the number format of the column's first data
cell. Excel decides per cell (it caches date-formatted cells as <d> and General
ones as <n>), so a General first cell made every date sort as a number, and a
date-formatted first cell made General numbers sort as dates. The source now
records, per cell, whether its own format is a date, and the class follows that.
2026-10-14 12:40:09 -04:00
Local contributor 0739f71fac PivotTables: only pivot cache dates count real days from 1899-12-30
The previous commit changed the shared ISO date parser, so worksheet t="d"
cells dated before March 1900 also read one day later. The evidence for the
real-day convention comes from Excel's pivot caches only, so worksheet cells
read exactly as before again. The parser takes the date conversion as a
parameter: worksheet cells keep DATE() rules, pivot cache items use the
real-day conversion that the cache writer mirrors.
2026-10-14 09:19:06 -04:00
Local contributor b60d37e4e9 PivotTables: date items sort after logicals and errors
The ascending item order put dates between text and TRUE/FALSE. Excel's item
lists put numbers, text, logicals, errors, dates and then blanks: in the one
Excel-saved cache in the test corpus whose fields mix dates with logicals or
errors (ClosedXML VariousDataTypesInTableColumns), the Mixed Types field lists
10, 14.5, ABC, TRUE, #DIV/0!, 16:30, 8/10/2020, (blank), and the DateTime with
num field puts its numbers before its dates. The sort classes follow that order.

Also adds the regression test for the time items read from an Excel cache.
2026-10-14 09:11:28 -04:00
Local contributor fadcec3683 PivotTables: cached times and dates before March 1900 name the right items
Excel writes a pivot cache's date items as ISO dates counting real days from
1899-12-30: a time is 1899-12-30T08:00:00 and serial 1 is 1899-12-31. GridCraft
read them with DATE() rules, which move year 1899 on to 3799, so those items
never matched the report's items. A refresh then put them after every item that
did match, such as (blank), and saving wrote that wrong order into the file.

ISO dates (pivot cache items, t="d" cells) now go through a calendar-date
conversion that counts real days from the epoch, accepts 1900-02-29 as serial
60, and in the 1904 system takes 1899-12-30 as a time's date part. The cache
writer uses the inverse, so serial 1 is written as 1899-12-31 as Excel does.
DATE() keeps its own rules.
2026-10-14 09:11:28 -04:00
Local contributor e16b95eb82 XLSX: Multi-level PivotChart categories plot one label per point; quoted series names survive a save
A PivotChart whose multiLvlStrRef categories cover two levels (Graph!$A$4:$B$7 for 4 points) stayed live when the innermost column matched the cache. The renderer reads every cell of that block, so the chart drew 8 labels for 4 points, and a save flattened it into an 8-point strRef. Such a block is now compared cell for cell like any other reference: its cell count isn't the point count, so the innermost level is plotted from the cache, one label per point, and saved as a strLit. A one-level reference whose cells hold the cache still stays live.

A literal series name is stored as a quoted formula literal with doubled quotes ("Sales ""East"""), which stale PivotChart series now always get. The chart and chartex writers only stripped the outer quotes, so the name came back as Sales ""East"" after a save. Both writers now unescape the literal through one helper.
2026-10-14 08:22:29 -04:00
neilcawseandClaude Opus 5.5 df4599d2cd XLSX: PivotChart series keep live cells only when they hold the cache
A PivotChart series stayed live whenever its reference had as many cells
as the cache had points. With one row item, every formula pointing at the
PivotTable's corner cell passed that test, so the chart plotted the header
text. Multi-level category references never passed it (width × height
cells for N points), so a correct reference was replaced by a leaf-only
literal and its outer level was lost on save.

The check now compares values, once every sheet is read (read_chart
returns each PivotChart series' cache; plot_pivot_caches runs after the
sheets load): a series plots its cache unless the referenced cells hold
the cached points, numbers within rounding and text as is. For a
multiLvlStrRef, the innermost level's column (or row) is compared, so a
reference that matches stays live and is saved as a reference.

Literals read before this branch keep their points again: a missing,
unreadable or too small ptCount gives way to the points present, and
points without an idx go in document order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 14:14:53 -04:00
neilcawseandClaude Opus 5.5 374ab0f127 XLSX: PivotCharts plot their cached points; deleted automatic titles stay off
Excel often saves a PivotChart series with formulas that only approximate
its PivotTable: every formula pointing at the table corner cell, or a block
that takes in the grand total row. Excel draws the chart from the
PivotTable, so the cached points are what it shows; GridCraft evaluated the
formulas and drew empty charts or a stray grand total bar. When a PivotChart
series references don't cover their cached points (numCache, strCache or the
innermost multiLvlStrCache level), the series now plots the cached points
and cached name as array constants. Refreshing the PivotTable rebinds the
chart to live cells as before.

A chart with <c:autoTitleDeleted val="1"/> and no title now opens with its
automatic title off, instead of showing the lone series name ("Series1").

Array-constant series also survive a save: literals are read by index and
ptCount (gaps stay #N/A instead of shifting later points), and written by
parsing the array constant, so text with quotes, commas or semicolons is
kept.

Literal values keep their number format: Series gains number_format, read
from the numLit or numCache formatCode and written as the numLit
formatCode (it was always General). The renderer uses it only for array
constants; references keep using their cells' format. Cached PivotChart
points now label as "$185" or "5.36%", as in Excel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 14:14:53 -04:00
neilcawse add4ebf5d8 PivotTables: custom subtotals on the first axis field keep the table's subtotal default on 2026-10-13 13:42:46 -04:00
neilcawse 8fc6aa7082 PivotTables: sort scopes keyed by date grouping, custom subtotals, date order of date groups
- Sort scope entries name their field by source column and date grouping
  (PivotScopeItem), so Years and Quarters of one date column stay apart when
  reading, computing and writing.
- The engine and the writer resolve a scope the same way: a scope naming an
  item that's no longer there sorts by the grand total, as it is then saved.
- A field with custom subtotal functions (sumSubtotal...varPSubtotal) has
  subtotals on; it shows the automatic subtotal, with a warning.
- Date groups that aren't sorted show in date order, the order of the cache's
  group items, instead of source order.
2026-10-13 13:42:46 -04:00
neilcawse ce8f5fca22 PivotTables: a sort by value keeps its scope, and more refresh fidelity
- Sort by the values in a column (autoSortScope references naming items of the
  other axis): read, written back and used by the engine, instead of sorting by
  the grand total. A scope GridCraft can't represent loads as a sort by label,
  with a warning.
- Changing subtotals in Design replaces each field's own subtotal setting.
- A numeric "For empty cells show" caption (Excel stores missingCaption="0")
  is written as a number in the value's format.
- With field headers off there's no Values row, so firstDataRow matches.
- A field that isn't auto-sorted keeps its <items> order even when it is cache
  order (date groups only when reordered).

Items tied in a sort by value still break ties by label in the sort
direction: over 60 tie groups in the 11 Excel-saved reports no stored order
(pivotField items, sharedItems, first appearance, reversed or not) explains
more than 21, the same as the current rule.
2026-10-13 13:42:46 -04:00
neilcawseandClaude Opus 5.5 bf15f965ae PivotTables: refresh keeps sort by value, captions, item order and layout settings
A refreshed PivotTable read from an Excel file now lays out like Excel's:
- Sort by a value field (autoSortScope on data field n): PivotField.sort_by, applied within
  each parent; pivot.sort takes `by: "Sum of X"`.
- Captions: rowHeaderCaption, colHeaderCaption, dataCaption, grandTotalCaption and
  missingCaption (For empty cells show), field custom names and renamed items (item n).
- Manual item order of fields that aren't auto-sorted.
- Per-field subtotals (defaultSubtotal, with the table default in pivotTableDefinition16),
  Repeat Item Labels (fillDownLabels), field number formats, the Values row
  (hideValuesRow) and the classic layout (gridDropZones).
- rowGrandTotals/colGrandTotals were read and written the wrong way round.
- Date items sort after text, as in Excel.

All settings are written back to XLSX.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 13:42:46 -04:00
vangel76andClaude Sonnet 5.5 cde1dbb2e4 Merge main into #795
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 19:10:18 +02:00
Alisson Freitas de Araujo c77b8ac3cb Merge pull request #1 from scottcampbelldata/fix/pr-259-main-integration
Repair current-main integration and new table-column metadata (#259)
2026-10-13 12:40:20 -03:00
scottcampbelldata 270995c299 #259: repair integration with current main 2026-10-13 10:13:15 -04:00
Sebastian Whincop 6f8c4d09c7 Merge storytold/main into fix/excel-snap-to-zero
Take main's ROADMAP.md (the previous merge had dropped main's print rows;
this PR doesn't edit the roadmap). In eval.rs keep the snapping SUM fold
and pass the workbook date system to binary_scalar_snapped, as main now
does for binary_scalar.
2026-10-13 21:52:12 +13:00
AlissonFA 1e865962dc xtask: normalize CRLF in parity and keytips check steps 2026-10-12 22:57:30 -03:00
AlissonFA 9f224b6ca9 engine: test unfiltered column on column C so it is not absorbed by table auto-expansion 2026-10-12 22:45:58 -03:00
AlissonFA a5bcbe5c05 Merge origin/main into feat/table-auto-expansion 2026-10-12 22:44:07 -03:00
Sebastian Whincop e07b5e39b0 Merge storytold/main into fix/excel-snap-to-zero
Catch up with main now that its CI is green again.
2026-10-13 13:23:19 +13:00
vangel76andClaude Sonnet 5.5 7d3516ab33 Calc: SUBTOTAL(10x) recalculates when Row Height, AutoFit Row Height or Ungroup reveal rows
home.rowHeight, home.autofitRowHeight and data.ungroup change row hidden
state without marking the edit structural, so SUBTOTAL(101-111) kept a stale
value. Found by the command-sequence fuzz (seed 3).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 21:44:04 +02:00
vangel76andClaude Sonnet 5.5 a7e1a4a99b Quick Analysis: button tests, several-areas refusal, more formatting tiles (#791)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 21:05:29 +02:00
vangel76andClaude Sonnet 5.5 4972675b1b UI: Quick Analysis (Ctrl+Q) (#791)
A corner button on multi-cell selections and Ctrl+Q open a popup of one-click
analyses (formatting, charts, totals, tables, sparklines). Totals and sparklines
are new engine commands, analysis.addTotal and analysis.addSparklines, each one
undo step, never overwriting data unless asked.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 21:03:01 +02:00
Sebastian Whincop d38ebe3853 Merge storytold/main into fix/excel-snap-to-zero
Resolve the test-file conflicts (both sides appended tests) and keep
SUM's snap in main's in-place SUM/COUNT/AVERAGE fold: the fold adds
SUM's numbers one by one and snaps only the last addition, as
gridcraft_core::arith::sum_snapped does.
2026-10-12 17:13:19 +13:00
AlissonFA 21672fea59 engine: harden multi-cell table expansion and drop unrelated parse.rs date change 2026-10-11 13:15:59 -03:00
AlissonFA 3bbd2afb0f engine: translate Portuguese comments and test fixtures in tables.rs to English 2026-10-11 03:53:46 -03:00
AlissonFA 871b025921 engine: inherit column format on expanding cell and support d/m/y dates 2026-10-11 03:32:19 -03:00
AlissonFA 51a6d64c23 engine: formatting empty cell adjacent to table does not trigger auto-expansion 2026-10-11 03:04:59 -03:00
AlissonFA 4629c063ab engine: rustfmt tables.rs after table auto-expansion 2026-10-11 02:57:20 -03:00
AlissonFA e765690c18 engine: test table auto-expansion edge cases (totals row, diagonal, overlap, undo) 2026-10-11 02:52:39 -03:00
AlissonFA 0d0e6d5e39 engine: auto-expand table column to the right with unique header generation 2026-10-11 02:49:30 -03:00
AlissonFA c39fcd884e engine: extend data validation ranges on table row auto-expansion 2026-10-11 02:42:29 -03:00
AlissonFA 8d495f9ce0 engine: propagate calculated formulas and styles on table row expansion 2026-10-11 02:38:25 -03:00
AlissonFA 85ab340ccd engine: auto-expand table range when typing into row below 2026-10-11 02:26:42 -03:00
Sebastian Whincop 27fc0e828f Accuracy: snap a LAMBDA body by its own root
Excel treats a LAMBDA body as a formula of its own, so the snap to zero
(an add or subtract of opposite-sign operands that cancels to less than
2^(e-49) of the left operand becomes exactly 0) applies to a body whose
root is an add or subtract, by the same root rule as a cell and as a
defined name's body. A LAMBDA probe on Windows Excel 16.0.20430 (126
formulas) shows it in every context probed: a named lambda in 9 positions
(=L(x,y), *1, +0, 0+, (..), -.., SUM, IF, ABS), inline lambdas, LET-bound
lambdas, and MAP, REDUCE, SCAN, MAKEARRAY, BYROW and BYCOL. A bare x-y body
(or a lambda that calls one) snaps; a parenthesised, unary, IF, inner-step,
+0 or LET body keeps its residue. A review probe (34 more cells) showed the
same 7-ulp/8-ulp threshold inside a body, element-wise snapping of array
arguments, and that curried and nested lambdas, 0+x-y and a LET closure
snap by the root of the inner body, while a body that returns a reference
still returns one.

- calc: call_lambda_values, the one place a LAMBDA body is evaluated for
  every call route, evaluates a body whose root is an add or subtract with
  value_root (which charges its own depth). Any other body, including one
  with a LET or IF at its root, is evaluated as before.
- tests: 10 body shapes x 9 positions with signs, inline and LET-bound
  lambdas, one snapping and one non-snapping body under each higher-order
  function, array arguments, the threshold inside a body, curried, nested
  and closed-over bodies, a guard that reference-returning bodies still
  return a reference, and a self-recursive lambda ending in an error.

Evidence: the 126-formula probe matched Excel on 92 rows before and matches
on all 126 now; the Spreadsheet Accuracy Suite's formula rows show no new
failures, and the 297-row snap probe and the 96-row name probe are
unchanged. Conditional-formatting and data-validation formulas and Mac
Excel were not probed.

	modified:   crates/calc/src/eval.rs
	modified:   crates/calc/src/tests.rs
2026-10-11 17:19:52 +13:00
Sebastian Whincop c0f4480504 Accuracy: snap a defined name's body, and only the root in Evaluate Formula
Excel treats a defined name's body as a formula of its own, so the snap to
zero (an add or subtract of opposite-sign operands that cancels to less than
2^(e-49) of the left operand becomes exactly 0) applies to the body by the
same root rule as a cell, wherever the name is used. A name probe on Windows
Excel 16.0.20430 (8 name bodies in 12 positions: =N, =N*1, =N+0, =0+N, =(N),
=-N, =+N, =SUM(N), =IF(TRUE,N), =ABS(N), =1*N, =N-0) shows the result depends
only on the body's shape: a body that is a bare subtraction, a SUM's last
addition, or a name for one snaps everywhere; a parenthesised, unary, IF,
inner-step or +0 body keeps its residue everywhere. Sheet-scoped names and
array-valued names behave the same way in Excel. The 8 bodies use a gap of
one ulp; the threshold for name bodies rests on request 3's
lookup-shapes.xlsx (Sheet1!H15:H26: =Gap, =Gap*1, =Gap+0 are 0 for gaps of
1, 4 and 7 ulps, and the 8-ulp gap keeps 1.78e-15). This is the case the
suite leaves undecided:name-snap.

- calc: Evaluator::name evaluates a body whose root is an add or subtract
  with value_root. Any other body, a range included, is evaluated as before,
  so range-valued names still refer to their range. A name that points at
  another name inherits the snap through the existing recursion.
- calc: value_root charges its own level of the depth budget. It bypasses
  Evaluator::eval, so without this a chain of names cost half the depth and
  recursive names nested through cells could overflow the stack.
- calc: evaluate_inner_expr evaluates a sub-expression without the root snap.
- engine: Evaluate Formula uses the root snap for the root step only. An
  inner step of =(A1-B1) used to show 0 while the cell showed the residue.
- tests: 8 bodies x 12 positions with signs, Excel's own Gap shapes, range-,
  array- and sheet-scoped names, self-referential and long name chains, a
  guard that range-valued names still refer to their range, and the
  Evaluate Formula steps.

Evidence: the 96-row name probe matched Excel on 72 rows before and matches
on all 96 now; the Spreadsheet Accuracy Suite's formula rows show no new
failures and the 297-row snap probe is unchanged.

	modified:   crates/calc/src/eval.rs
	modified:   crates/calc/src/recalc.rs
	modified:   crates/calc/src/tests.rs
	modified:   crates/engine/src/cmd/formulas.rs
	modified:   crates/engine/src/tests.rs
2026-10-11 16:54:50 +13:00
Sebastian Whincop 669f9cc53d Accuracy: Excel's snap to zero at a formula's root and in SUM
Excel returns exactly 0 when an add or subtract of opposite-sign operands
cancels to less than 2^(e-49), e the binary exponent of the LEFT operand.
It does this only at the bare root of a formula (=A-B, the end of =0+A-B)
and in the last addition of every SUM, never inside parentheses, unary
signs, IF branches or inner steps. GridCraft returned the IEEE residue
(=1-1.0000000000000002 gave -2.2e-16, =0.1+0.2-0.3 gave 5.5e-17).

- core: arith::snap_add and arith::sum_snapped
- calc: Evaluator::value_root applies the snap at the formula root
- functions: SUM uses sum_snapped
- tests: unit tests for the threshold and operand edge cases, evaluator
  tests for snapped and not-snapped shapes (including =SUM(A-B) and
  =A-B-0, which Excel does not snap), error and text operands, and a
  binade-crossing case

Evidence: the Spreadsheet Accuracy Suite's high-confidence formula rows go
from 488 failures to 47 with no regressions, and 297 probe rows recalculated
by Windows Excel 16.0.20430 (11 magnitudes, 6-10 ulp thresholds, negative
left operands, SUM shapes) match bit for bit; the unfixed code matched 174.

	modified:   crates/calc/src/eval.rs
	modified:   crates/calc/src/recalc.rs
	modified:   crates/calc/src/tests.rs
	new file:   crates/core/src/arith.rs
	modified:   crates/core/src/lib.rs
	modified:   crates/functions/src/math.rs
2026-10-11 16:25:10 +13:00
521 changed files with 75099 additions and 2950 deletions
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+117
View File
@@ -0,0 +1,117 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/gridcraft",
"repository_id": 1408285582,
"producer_workflow_id": 429713469,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "gridcraft-nightly-20261124",
"repository": "storytold/gridcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135773,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_gridcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_gridcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "browser-print-probe"
version = "0.1.0"
edition = "2024"
publish = false
[lib]
crate-type = ["cdylib"]
[workspace]
[dependencies]
craft-print = { path = "../../shared/crates/print" }
wasm-bindgen = "=0.2.129"
+190
View File
@@ -0,0 +1,190 @@
"""Use real Chrome print preview on an isolated runner, then inspect the saved PDFs."""
import functools
import http.server
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import threading
import time
import sys
from PIL import Image, ImageGrab
from reportlab.pdfgen import canvas
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
SITE = Path(__file__).resolve().parent
RESULTS = Path("browser-capture").resolve()
COLORS = {"first": [(220, 40, 50), (25, 55, 215)], "second": [(0, 160, 45)]}
def fixture(name, colors):
doc = canvas.Canvas(str(SITE / f"{name}.pdf"), pagesize=(612, 792))
for index, rgb in enumerate(colors):
doc.drawString(72, 690, f"{name} document page {index + 1}")
doc.setFillColorRGB(*(v / 255 for v in rgb))
doc.rect(145, 245, 322, 302, fill=1, stroke=0)
doc.showPage()
doc.save()
def wait_for_pdf(before, name):
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
found = set(RESULTS.glob("*.pdf")) - before
if len(found) > 1:
raise RuntimeError(f"multiple outputs for {name}: {found}")
if found:
path = next(iter(found))
if path.read_bytes().rstrip().endswith(b"%%EOF"):
return path.rename(RESULTS / f"{name}-captured.pdf")
time.sleep(0.25)
raise TimeoutError(f"{name} produced no complete PDF")
def inspect_pdf(path, colors):
info = subprocess.check_output(["pdfinfo", path], text=True)
pages = next(int(line.split()[1]) for line in info.splitlines() if line.startswith("Pages:"))
assert pages == len(colors), (path, pages, colors)
prefix = path.with_suffix("")
subprocess.run(["pdftoppm", "-r", "36", "-png", path, prefix], check=True)
for index, rgb in enumerate(colors, start=1):
with Image.open(f"{prefix}-{index}.png") as image:
actual = image.convert("RGB").getpixel((image.width // 2, image.height // 2))
assert max(abs(a - b) for a, b in zip(actual, rgb)) < 20, (index, actual, rgb)
print(f"{path.name} page {index}: {actual}", flush=True)
def wait_preview(name, color, visible):
"""Observe the actual X11 surface. The host page contains no colour marks."""
deadline = time.monotonic() + 40
while True:
image = ImageGrab.grab().convert("RGB")
# A half-page solid rectangle survives Chrome's print-preview scaling.
pixels = image.resize((320, 240)).getdata()
count = sum(max(abs(a - b) for a, b in zip(pixel, color)) < 18 for pixel in pixels)
if (count > 300) == visible:
image.save(RESULTS / f"{name}.png")
print(f"{name}: {count} matching preview pixels", flush=True)
return
if time.monotonic() >= deadline:
image.save(RESULTS / f"{name}-timeout.png")
raise TimeoutError(f"{name}: matching preview pixels = {count}")
time.sleep(0.35)
def cancel_then_save(driver, *, gtk_picker=False):
before = set(RESULTS.glob("*.pdf"))
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "first"))).click()
wait_preview("before-cancel", COLORS["first"][0], True)
subprocess.run(["xdotool", "key", "Escape"], check=True)
wait_preview("after-cancel", COLORS["first"][0], False)
assert set(RESULTS.glob("*.pdf")) == before, "cancel created a PDF"
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "second"))).click()
wait_preview("next-document", COLORS["second"][0], True)
subprocess.run(["xdotool", "key", "Return"], check=True)
if gtk_picker:
# Firefox's GTK dialog has already focused the filename when it covers
# the green preview. The selected filename stem excludes its extension.
wait_preview("gtk-file-picker", COLORS["second"][0], False)
subprocess.run(["xdotool", "key", "ctrl+a"], check=True)
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
subprocess.run(["xdotool", "key", "Return"], check=True)
# Chrome's Save as PDF destination opens the native Save File dialog.
deadline = time.monotonic() + 25
while not gtk_picker and time.monotonic() < deadline:
if set(RESULTS.glob("*.pdf")) != before:
break
title = subprocess.run(["xdotool", "getwindowfocus", "getwindowname"], capture_output=True, text=True)
# Firefox's GTK picker can be a transient without a separate window title.
image = io.BytesIO()
ImageGrab.grab().save(image, format="PNG")
words = subprocess.run(["tesseract", "stdin", "stdout", "--psm", "6"], input=image.getvalue(), capture_output=True, check=True).stdout.decode()
if "save" in title.stdout.lower() or ("Name:" in words and "Save" in words):
print("Native Save File dialog is visible", flush=True)
subprocess.run(["xdotool", "key", "ctrl+l"], check=True)
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
subprocess.run(["xdotool", "key", "Return"], check=True)
break
time.sleep(0.25)
pdf = wait_for_pdf(before, "after-cancel")
inspect_pdf(pdf, COLORS["second"])
assert set(RESULTS.glob("*.pdf")) == before | {pdf}
def firefox_probe(url):
options = webdriver.FirefoxOptions()
options.set_preference("print_printer", "Mozilla Save to PDF")
options.set_preference("print.save_print_settings", True)
with webdriver.Firefox(options=options, service=FirefoxService(shutil.which("geckodriver"))) as driver:
print("Firefox", driver.capabilities["browserVersion"], flush=True)
driver.get(url)
try:
driver.find_element(By.ID, "control").click()
yellow = (240, 185, 20)
wait_preview("firefox-parent-preview", yellow, True)
subprocess.run(["xdotool", "key", "Escape"], check=True)
wait_preview("firefox-parent-dismissed", yellow, False)
cancel_then_save(driver, gtk_picker=True)
finally:
ImageGrab.grab().save(RESULTS / "firefox-last-screen.png")
def main():
RESULTS.mkdir()
for name, colors in COLORS.items():
fixture(name, colors)
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=SITE)
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{server.server_port}/"
# This disposable browser cannot contact the system CUPS server.
os.environ["CUPS_SERVER"] = str(RESULTS / "absent-cups.sock")
if "--firefox" in sys.argv:
firefox_probe(url)
return
options = webdriver.ChromeOptions()
cancellation = "--cancel" in sys.argv
if not cancellation:
options.add_argument("--kiosk-printing")
options.add_argument("--no-first-run")
options.add_experimental_option("prefs", {
"download.default_directory": str(RESULTS),
"savefile.default_directory": str(RESULTS),
"printing.print_preview_sticky_settings.appState": json.dumps({
"version": 2, "recentDestinations": [{"id": "Save as PDF", "origin": "local"}],
"selectedDestinationId": "Save as PDF",
}),
})
options.set_capability("goog:loggingPrefs", {"browser": "ALL"})
with webdriver.Chrome(options=options, service=Service(shutil.which("chromedriver"))) as driver:
print("Chrome", driver.capabilities["browserVersion"], flush=True)
driver.get(url)
try:
if cancellation:
cancel_then_save(driver)
return
for name in ("control", "first", "second"):
before = set(RESULTS.glob("*.pdf"))
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, name))).click()
pdf = wait_for_pdf(before, name)
if name == "control":
text = subprocess.check_output(["pdftotext", pdf, "-"], text=True)
assert "Parent page control only" in text, text
else:
inspect_pdf(pdf, COLORS[name])
finally:
(RESULTS / "browser-log.json").write_text(json.dumps(driver.get_log("browser"), indent=2))
driver.save_screenshot(str(RESULTS / "last-view.png"))
if __name__ == "__main__":
main()
+22
View File
@@ -0,0 +1,22 @@
<!doctype html>
<meta charset="utf-8">
<title>Parent page control</title>
<style>
#control-marker { display: none; }
@media print { #control-marker { display: block; } }
</style>
<p>Parent page control only</p>
<svg id="control-marker" width="360" height="340"><rect width="360" height="340" fill="rgb(240,185,20)"/></svg>
<button id="control" onclick="setTimeout(() => window.print(), 0)">Print parent</button>
<button id="first" disabled>Print first PDF</button>
<button id="second" disabled>Print second PDF</button>
<script type="module">
import init, { print_document } from "./pkg/browser_print_probe.js";
await init();
for (const id of ["first", "second"]) {
const pdf = new Uint8Array(await (await fetch("./" + id + ".pdf")).arrayBuffer());
const button = document.getElementById(id);
button.addEventListener("click", () => print_document(pdf));
button.disabled = false;
}
</script>
+7
View File
@@ -0,0 +1,7 @@
use wasm_bindgen::prelude::*;
/// Exercise the same shared entry point as the GridCraft web print service.
#[wasm_bindgen]
pub fn print_document(bytes: &[u8]) -> Result<(), JsValue> {
craft_print::browser::print_pdf(bytes).map_err(|error| JsValue::from_str(&error))
}
+4
View File
@@ -9,7 +9,11 @@ workflows:
'.github/workflows/lockfile.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]'
'.github/workflows/nightly-dispatch.yml': []
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/notify-services.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]'
+71
View File
@@ -0,0 +1,71 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [GridCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
if: >-
github.repository == 'storytold/gridcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/gridcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/gridcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/gridcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/gridcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'gridcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+59
View File
@@ -0,0 +1,59 @@
name: GridCraft release-ref nightly signer
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: gridcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/gridcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: main
app-name: gridcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# Forward exactly the secrets the signer's sign steps read, named explicitly (never `inherit`),
# as the stable Release caller does. The callee must declare them; it does since the shared
# change that added them, and `uses:` is pinned to that revision.
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
+35
View File
@@ -0,0 +1,35 @@
name: GridCraft unsigned nightly
# Automated daily nightly builds at 03:30 UTC (plus manual dispatch by reviewed manual actors).
on:
schedule:
- cron: '30 3 * * *'
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/gridcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: main
app-name: gridcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged 8389cad8 (#375, the signer Windows fix).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+21 -2
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", ".github/nightly-linux-signing-key.asc", "packaging/**", "assets/app-icon/**", "sonar-project.properties"]
workflow_dispatch:
permissions:
@@ -22,6 +22,25 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/[email protected]
with:
egress-policy: audit
- uses: actions/[email protected]
with:
persist-credentials: false
- name: Run the synthetic nightly packaging suites
run: python3 packaging/nightly-tests.py
- name: Check the committed nightly icons still match their provenance
run: python3 packaging/nightly-icons.py --check
windows-install-policy:
timeout-minutes: 10
name: Windows installation policy (no app build)
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
@@ -0,0 +1,47 @@
name: Verify browser print output
on:
push:
branches: [verify/gridcraft-browser-output-4859]
permissions:
contents: read
jobs:
browser-print:
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
repository: storytold/craft-libs
ref: e0646e91ad432c43358137d0d894877216fa91ed
path: shared
- uses: storytold/craft-common-actions/actions/install-apt-packages@main
with:
packages: xvfb xauth xdotool tesseract-ocr poppler-utils python3-selenium python3-reportlab python3-pil
- name: Build the shared browser entry point as WebAssembly
working-directory: .github/print-probe
env:
CARGO_PROFILE_DEV_DEBUG: 0
run: |
set -euo pipefail
rustup target add wasm32-unknown-unknown
cp ../../shared/Cargo.lock Cargo.lock
cargo build --target wasm32-unknown-unknown
archive="$RUNNER_TEMP/wasm-bindgen.tar.gz"
curl --fail --location --silent --show-error https://github.com/wasm-bindgen/wasm-bindgen/releases/download/0.2.129/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl.tar.gz -o "$archive"
echo "82d12bb940e2d4e72e0d5605387fc1b8ca179044e012b620f0ce4e7440e8320e $archive" | sha256sum --check
tar -xf "$archive" -C "$RUNNER_TEMP" wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen
"$RUNNER_TEMP/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen" --target web --out-dir pkg target/wasm32-unknown-unknown/debug/browser_print_probe.wasm
- name: Verify the Firefox print dialog and inspect its output
run: |
firefox --version
geckodriver --version
xvfb-run -a /usr/bin/python3 .github/print-probe/capture.py --firefox
- name: Preserve output and diagnostics
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
with:
name: firefox-print-output
path: browser-capture
if-no-files-found: warn
retention-days: 7
+6
View File
@@ -8,3 +8,9 @@ plan/
/.claude/
/target-*/
/craft-fonts/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
/.nightly-tools
/.nightly-input
/craft-i18n
__pycache__/
-69
View File
@@ -1,69 +0,0 @@
# Accessibility
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
## Supported environments and how accessibility works
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
- **macOS:** NSAccessibility (VoiceOver)
- **Linux and FreeBSD:** AT-SPI (Orca)
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
## Known limitations and workarounds
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
See [This application](#this-application) below for repository-specific links and details.
## Reporting an accessibility barrier
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
- **Helpful details to share (when convenient):**
- What you were trying to do, what happened, and what you expected
- Application version (or commit) and operating system or browser
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
## How we respond
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
## Note for contributors and coding agents
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
## Ownership
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
## This application
**GridCraft** (`storytold/gridcraft`) is an open-source spreadsheet application written in pure Rust.
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
- **Command-line and automation interface:** `gridcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
- **Report an accessibility barrier:** [Open an issue in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues/new)
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/gridcraft`](https://github.com/storytold/gridcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
+1
View File
@@ -81,4 +81,5 @@ Paths and conventions:
- Test corpora live in a separate corpus repository, pinned and sha256-verified. Test workbooks are built in code.
- Progress log: `ROADMAP.md`. `plan/` is an optional gitignored notebook.
- Run with a control channel: `cargo run --release -p gridcraft -- --sample sales --control 7979`. Drive it with `gridcraft-cli send 7979 <method> '<json>'`; methods are in `crates/ui-egui/src/control.rs`, the protocol in `docs/control-protocol.md`. Offscreen render: `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli mcp`.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog id `headless: yes` only when the engine registry (what `gridcraft-cli` and the MCP server load) has it. A missing id takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs`, or reads `unknown`. When a command lands, delete its mark; the check fails on a stale one.
- Docs: `ROADMAP.md`, `docs/gaps.md` (ranked work), `docs/architecture.md`, `docs/target-app-parity.md`, `docs/roadmap.md`, `docs/contributors.md`.
+7
View File
@@ -13,6 +13,7 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
| `epaint_default_fonts::NOTO_EMOJI_REGULAR` (dependency font input) | The Noto Project Authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Noto Emoji](https://fonts.google.com/noto/specimen/Noto+Emoji) | SIL Open Font License 1.1 (full upstream text in `NOTICE`) | NotoEmoji-Regular.ttf is enabled by egui's `monochrome_emoji_fonts` feature and used as the monochrome emoji fallback. Dependency asset unmodified here, no font file copied into this repository. |
| `epaint_default_fonts::UBUNTU_LIGHT` (dependency font input) | Canonical Ltd. and the Ubuntu Font Family authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Ubuntu font](https://design.ubuntu.com/font) | Ubuntu Font Licence 1.0 (full upstream text in `NOTICE`) | Ubuntu-Light.ttf is egui's default proportional face. Dependency asset unmodified here, no font file copied into this repository. |
| Regional format data in `crates/core/src/region.rs` (data, no file of its own) | Unicode, Inc. (Unicode CLDR) | [cldr-json](https://github.com/unicode-org/cldr-json) (`cldr-numbers-full`, `cldr-dates-full`) and ICU's CLDR 48 data | Unicode License v3 (`Unicode-3.0`; full text in `NOTICE`) | Separators, month and weekday names, AM/PM words, currency symbols and date order of the built-in regions. No CLDR file is copied into this repository. |
| Polish formula function names in `crates/formula/src/input/pl.rs` (data, no file of its own) | PhpSpreadsheet Authors | [PhpSpreadsheet `locale/pl/functions`](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Calculation/locale/pl/functions) | MIT (Copyright (c) 2019-2026 PhpSpreadsheet Authors; full upstream text in `NOTICE`) | The English-to-Polish function name table (`FUNCTIONS`). Names not in that table come from Microsoft's pl-pl support pages and #1678's Excel for the web observation. No PhpSpreadsheet file is copied into this repository. |
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
| `docs/brand/artcraft-logo.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
@@ -38,6 +39,12 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.gridcraft.png` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, Linux hicolor render |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.gridcraft.svg` | GridCraft contributors | original (hand-written SVG; `packaging/icons.sh`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Placeholder icon, copy of gridcraft.svg |
| `assets/app-icon/gridcraft-nightly.svg` | GridCraft contributors | original (the stable placeholder artwork with only its field colour deepened; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly (nightly-v1) icon master |
| `assets/app-icon/gridcraft-nightly.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, 256 px (Linux tar and runtime window icon) |
| `assets/app-icon/gridcraft-nightly-1024.png` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg` on the 824/1024 Mac grid; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly icon, padded Mac master |
| `assets/app-icon/gridcraft-nightly.icns` | GridCraft contributors | original (PNG slots packed from `gridcraft-nightly.svg` renders; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS bundle icon |
| `assets/app-icon/gridcraft-nightly.ico` | GridCraft contributors | original (rendered from `gridcraft-nightly.svg`; `packaging/nightly-icons.py`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows exe icon |
| `assets/app-icon/nightly-provenance.json` | GridCraft contributors | original (written by `packaging/nightly-icons.py`) | MIT OR Apache-2.0 | Hashes and method of the nightly icon derivatives |
| `assets/app-icon/README.md` | GridCraft contributors | original | MIT OR Apache-2.0 | Icon documentation |
| `assets/app-icon/LICENSE.txt` | (licence text) | original | — | Licence of the app icon files |
| `docs/images/hero-sales.png` | GridCraft contributors | screenshot of GridCraft rendered offscreen (`crates/ui-egui/examples/snapshot.rs`) showing an original sample workbook | MIT OR Apache-2.0 | README screenshot; no third-party content |
Generated
+1457 -204
View File
File diff suppressed because it is too large Load Diff
+45 -33
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
[workspace.package]
version = "0.19.1"
version = "0.20.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -16,6 +16,7 @@ gridcraft-core = { path = "crates/core" }
gridcraft-numfmt = { path = "crates/numfmt" }
gridcraft-sandbox = { path = "crates/sandbox" }
gridcraft-formula = { path = "crates/formula" }
gridcraft-dax = { path = "crates/dax" }
gridcraft-functions = { path = "crates/functions" }
gridcraft-model = { path = "crates/model" }
gridcraft-calc = { path = "crates/calc" }
@@ -30,29 +31,30 @@ gridcraft-math = { path = "crates/math" }
# ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one
# craft-libs revision.
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] }
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd", version = "0.1.0", default-features = false }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0", default-features = false }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
# turn them into workbooks.
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" }
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
# SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx.
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
# foundation
thiserror = "2"
@@ -64,9 +66,11 @@ chrono = { version = "0.4.45", default-features = false, features = ["std", "clo
web-time = "1.1.0"
rayon = "1"
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
quick-xml = "0.41"
zip = { version = "3", default-features = false, features = ["deflate"] }
quick-xml = "0.42"
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
sha2 = { version = "0.11", default-features = false }
# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`).
sha1 = { version = "0.11", default-features = false }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
# equations: RaTeX (MIT) lays LaTeX out as positioned glyphs, rules and paths. Exact pins: it is
@@ -92,7 +96,15 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
epaint_default_fonts = "0.37"
# One native window per workbook: the window list, Window menu titles and the immediate-viewport
# driver. Same craft-libs revision as craft-update above.
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["ui"] }
# The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is
# to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the
# printer controls. Same craft-libs revision as above.
craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
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"] }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -120,18 +132,18 @@ debug = 0
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+29
View File
@@ -324,6 +324,35 @@ authorization of the copyright holder.
SPDX-License-Identifier: Unicode-3.0
The Polish formula function names in crates/formula/src/input/pl.rs (the English-to-Polish
name table) are taken from PhpSpreadsheet's locale/pl/functions table, under the MIT License.
Source: https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Calculation/locale/pl/functions
The following text is reproduced verbatim from PhpSpreadsheet's LICENSE:
MIT License
Copyright (c) 2019-2026 PhpSpreadsheet Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SPDX-License-Identifier: MIT
Linux Wayland window decorations
-------------------------------
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
+4
View File
@@ -165,6 +165,10 @@ directives, e.g. `RUST_LOG=debug` or `RUST_LOG=warn,gridcraft_engine=debug` (a t
matches a prefix: `gridcraft*=debug`). Runs with `GRIDCRAFT_NO_PREFS` set (no saved settings)
log to standard error only.
The `nightly-v1` channel keeps all of that in its own profile instead, which the Launcher names
(`--launch-profile nightly-v1 --profile-root <dir>`); a nightly build refuses to start without one,
so a Nightly run never touches the stable app's settings, prefs or logs.
## For agents: MCP, CLI and the control channel
```sh
+30 -1
View File
@@ -2,9 +2,10 @@
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (Polish formula language; earlier: File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX
is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web.
This page is the summary. The detail is in:
@@ -151,10 +152,15 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-31 | Recently Used lists the functions most recently entered in a formula from any source (ribbon, control channel, MCP, scripts), kept with the preferences and returned by `formulas.recentlyUsed`; the Insert Function dialog takes Excel's title and a working category list (Most Recently Used, All, each category) |
| 2026-10-31 | Formulas › Function Library as a big Insert Function button, the AutoSum split button and three columns of labelled small buttons, each category book in its own colour; category menus end with Insert Function… on that category; More Functions cascades into the remaining categories; Home › Editing shares the AutoSum menu; the MR key tip opens Recently Used |
| 2026-10-31 | System and embedded CJK fallback text shares the Latin baseline in cells, editors and window titles (#1265, #2621). Symbol and emoji alignment, manual row heights and clipping are unchanged |
| 2026-10-26 | Excel open check (`packaging/windows/excel-open-check`): saves workbooks with `gridcraft-cli`, opens each in real Excel through COM so a repair counts as a failure, and records pass or the failure per file; 0.12.1 over 18 public fixtures and 7 feature scenarios: 24 of 25 open cleanly, the other is the legacy-formula slowness of #410 |
| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) |
| 2026-10-25 | Charts: 100% Stacked Line and 100% Stacked Line with Markers (`insert.chart` `{type: "line", subtype: "stacked100"}` and `"stacked100Markers"`), drawn as each value's share of its category's total; XLSX `percentStacked` line charts open as 100% stacked instead of stacked |
| 2026-10-26 | PDF preserves Context/LTR/RTL reading direction through wrapping and drawing; RTL sheet cells, borders, headings, objects and sparklines mirror consistently |
| 2026-10-26 | Arabic PDF export shapes licensed glyph outlines and preserves searchable logical text; characters the font lacks, or a missing Arabic font, fall back to the standard fonts instead of failing the export |
| 2026-10-26 | Arabic bidi display/editing preserve logical source text; per-cell reading direction is editable and survives undo, XLSX and conditional-format priority |
| 2026-10-26 | Arabic text shows in cells and the interface through a system, fontconfig or craft-fonts Arabic face; workbook fonts keep their script fallbacks |
| 2026-10-26 | `cargo xtask bench`: ten fixed in-code workbooks (100k rows) time edits, formula entry, Calculate Now, sort and XLSX save/open, check their results and compare with a saved baseline. On an M2 Pro a 100k-dependent edit recalculates in 90–106 ms and 300k formulas in 395–455 ms |
| 2026-10-25 | Fill handle: from numbers, the right-drag menu offers Linear Trend and Growth Trend, which continue the best-fit line or exponential curve of the source (1, 2 gives 3, 4, 5 or 4, 8, 16) |
| 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before |
| 2026-10-24 | Macro interface ([macros.md](docs/macros.md#in-the-window)): an Automate › Macros group (Record Macro, which turns into Stop Recording, Use Relative References, Run Macro with recent macros); "Recording · N steps" with Stop in the status bar; a Record Macro dialog (checked name, free Ctrl+Shift shortcut, description); the Macros dialog lists macros beside Automate scripts and a VBA project, with Run, Step Into, Edit, Create, Delete and Options; Ctrl+Shift+letter macro shortcuts; questions that offer Run, Overwrite, Shift Down or Shift Right; a step editor with a breakpoint gutter, drag to reorder, a command picker, reference boxes that switch between relative tokens and absolute references, Inputs and Output tabs, a debug bar (Check, Run, Step, Continue, Run to Here, Stop with keep or undo) and grid overlays for inputs, writes, conflicts and the current step |
| 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) |
@@ -165,6 +171,9 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-24 | PivotTables: right-clicking a value, subtotal or grand total cell offers Show Details in the cell menu, which lists the cell's source records on a new sheet as double-clicking does |
| 2026-10-24 | Sheet tabs: dragging the handle between the tabs and the horizontal scrollbar gives the tabs more or less of the bar, as in Excel; each open workbook keeps its own share |
| 2026-10-24 | Charts: 100% Stacked Area (`insert.chart` `{type: "area", subtype: "stacked100"}`), drawn as each value's share of its category's total; XLSX `percentStacked` area charts open as 100% stacked instead of stacked |
| 2026-10-24 | XLSX charts keep what GridCraft doesn't model on save: an embedded chart that was not edited (moving or resizing aside) is written back from its original chart part, with its style, colour and user-shape parts, while every sheet its formulas name still exists; an edited chart is written from the model as before (#1668) |
| 2026-10-24 | XLSX: a password to modify (`fileSharing`) is kept on save, and opening such a file asks for the password or opens it read-only (never checked against Excel) (#921) |
| 2026-10-23 | File › Print › Settings offers Print Selection next to Print Active Sheets and Print Entire Workbook; several selected areas print one after the other, as in Excel |
| 2026-10-23 | Accounting negatives in text: `$(1,234)`, `$ (5)` and `(5)%` read as negative numbers when typed, coerced by arithmetic or passed to VALUE, like Excel 365; `(-5)`, `((5))`, `$5%` and dates or times in parentheses stay text |
| 2026-10-23 | Calc: `INDEX(A1:C3,2)` (one index on a reference of several rows and columns) is `#REF!` as in Excel, instead of the whole row; `INDEX(A1:C3,2,)` still gives the row |
| 2026-10-22 | Formula hardening: digits too many for a finite number are text, so `"1 <400 digits>/<400 digits>"` no longer coerces to NaN; a NaN column index in VLOOKUP, HLOOKUP and the D-functions is `#VALUE!` instead of an index underflow; REGEXREPLACE stops building a result as soon as it can only be too long (a worst case went from 1 GB to 7 MB) (#2163, #2162) |
@@ -184,14 +193,20 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change |
| 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS |
| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) |
| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root), with known differences in some `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) |
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
| 2026-10-15 | XLSX PivotTables on a data connection or the Data Model are kept on save (they were dropped), with the Data Model (`xl/model/item.data`) byte for byte; Excel opens the result without repair and refreshes it |
| 2026-10-15 | Keyboard: F8 Extend Selection and Shift+F8 Add or Remove Selection: arrows and clicks extend from the anchor or build multi-area selections without holding Shift or Ctrl, the status bar names the mode, and Esc, the key again or editing a cell ends it |
| 2026-10-14 | XLSX PivotTables whose source is a range or name in another workbook are kept on save (they were dropped): table, cache and records parts unchanged, style references renumbered; Excel opens the result without repair and refreshes it |
| 2026-10-14 | SORT, SORTBY and Data > Sort order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison |
| 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) |
| 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison |
| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate |
| 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift |
| 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) |
| 2026-10-14 | XLSX self-contained `extLst` entries are kept on save: x15 and x14 workbook properties, the workbook compatibility version and Excel for Mac entries, alongside calcFeatures; extensions that point at other content (slicers, timelines, data model, Google Sheets data) stay dropped and are named in an open warning |
| 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles |
| 2026-10-14 | XLSX: formulas opened with dynamic-array metadata (`cm`) keep it on save, with `xl/metadata.xml`. Before, a formula returning one value lost it (11 of 40 corpus files that have the part lost it entirely), and Excel recalculated some of them with implicit intersection (`SUMPRODUCT(IFERROR(...))` changed value) |
| 2026-10-14 | Recalculation: a dynamic array's anchor given a new formula that reads its old spill area (`A1` was `=SEQUENCE(3)`, becomes `=SUM(A2:A3)+1` or `=SEQUENCE(1,A2+1)`) sees that area empty instead of the old values |
@@ -209,6 +224,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) |
| 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) |
| 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained |
| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) |
| 2026-10-12 | GETPIVOTDATA reads PivotTable values by field and items (#284) |
| 2026-10-12 | PDF writer: objects are written straight to the output, identical pictures are stored once, style operators are emitted only when they change, `q` nesting is limited to 28 and polyline joins no longer leak into later strokes (#816) |
| 2026-10-12 | Insert › Text › WordArt (`insert.wordArt`, `wordArt.set`): floating decorative text with 10 original styles, outline and shadow, in-place editing, XLSX and print (#784) |
@@ -281,9 +297,11 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| Date | Change | Summary |
|---|---|---|
| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) |
| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; the roadmap qualifies XIRR's known `#NUM!` differences |
| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) |
| 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update |
| 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row |
| 2026-11-02 | minor | Polish formula language (`FormulaLocale::Pl`: 434 function names, PRAWDA/FAŁSZ, error values, table specifiers, `;` arguments, decimal comma) |
| 2026-11-02 | minor | Progress log: RefEdit reference boxes in dialogs |
| 2026-11-02 | minor | Progress log: Python mode in the formula bar |
| 2026-11-02 | minor | Progress log: Python cells as data |
@@ -296,13 +314,17 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-31 | minor | Progress log: Recently Used and Insert Function categories |
| 2026-10-31 | minor | Progress log: Function Library |
| 2026-10-31 | minor | Progress log: shared CJK/Latin baselines in cells, editors and window titles |
| 2026-10-26 | minor | Progress log: Excel open check |
| 2026-10-26 | minor | Progress log: PDF reading direction and RTL sheets |
| 2026-10-26 | minor | Progress log: Arabic PDF text |
| 2026-10-26 | minor | Progress log: Arabic bidi display and editing |
| 2026-10-26 | minor | Progress log: Arabic font fallback |
| 2026-10-26 | minor | Progress log: `cargo xtask bench` |
| 2026-10-25 | minor | Progress log: AutoSum over a selected row, and a selection's empty last row and column |
| 2026-10-24 | minor | Macro interface on the Automate tab; progress log row |
| 2026-10-24 | minor | Macro engine and `macro.*` commands; catalog 275 / 291 → 276 / 292 (View › Macros › Record Macro); progress log row |
| 2026-10-24 | trivial | Progress log: unedited embedded charts keep their XML on save (#1668) |
| 2026-10-24 | minor | Progress log: password to modify (#921) |
| 2026-10-23 | minor | Progress log: accounting negatives in number text |
| 2026-10-23 | minor | Progress log: INDEX with one index on a 2-D reference is #REF! |
| 2026-10-22 | trivial | Progress log: formula hardening (#2163, #2162) |
@@ -315,14 +337,21 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
| 2026-10-20 | minor | Dutch (nl) listed under other shipped languages; progress log row |
| 2026-10-19 | minor | Progress log: long flat operator chains (#916) |
| 2026-10-19 | trivial | Progress log: desktop theme portal read timeout |
| 2026-10-17 | minor | Conditional formatting: 2-/3-colour scale editor with per-stop type/value/colour, and in-place rule editing (part of #1165) |
| 2026-10-16 | minor | Progress log: undo steps share picture and macro bytes |
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers |
| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save |
| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes |
| 2026-10-14 | minor | Progress log: sorts order numbers exactly |
| 2026-10-14 | minor | Progress log: Set precision as displayed applied in calculation (#1343) |
| 2026-10-14 | minor | Progress log: `.xls` import reads cell formatting |
| 2026-10-14 | trivial | Progress log: XLSX PivotTables on another workbook kept on save |
| 2026-10-14 | minor | Progress log: lookups compare numbers exactly |
| 2026-10-14 | minor | Progress log: Analysis ToolPak value arguments reject multi-cell references |
| 2026-10-14 | trivial | Progress log: XLSX self-contained extLst entries kept on save |
| 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row |
| 2026-10-14 | minor | Progress log: spill anchor reading its old spill area |
| 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict |
+8 -1
View File
@@ -65,6 +65,13 @@ fn cond_format_list(s: &Sheet) -> Vec<String> {
cfs.iter().map(|c| format!("{:?} {:?} stopIfTrue={}", c.ranges, c.rule, c.stop_if_true)).collect()
}
/// The sheet's PivotTables: those modelled, and those kept unchanged for saving (their source is
/// in another workbook, a data connection or the Data Model).
fn pivot_count(s: &Sheet) -> usize {
let kept = s.preserved.as_deref().map_or(0, |p| p.rels.iter().filter(|r| !r.external && r.rel_type.ends_with("/pivotTable")).count());
s.pivots.len() + kept
}
fn diff_count(d: &mut Diffs, sheet: &str, a: usize, b: usize) {
if a != b {
d.push(|| format!("{sheet}: {a} → {b}"));
@@ -154,7 +161,7 @@ pub fn diff_workbooks(a: &Workbook, b: &Workbook, opts: &Options) -> Vec<Categor
}
diff_count(&mut comments, &name, sa.comments.len(), sb.comments.len());
diff_count(&mut hyperlinks, &name, sa.hyperlinks.len(), sb.hyperlinks.len());
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
diff_count(&mut pivots, &name, pivot_count(sa), pivot_count(sb));
}
let mut names = Diffs::new("names", m);
let name_list = |wb: &Workbook| -> BTreeSet<String> {
+100 -44
View File
@@ -16,11 +16,8 @@ pub(super) const REBUILT_KINDS: [&str; 1] = ["calcchain"];
// ---------------------------------------------------------------- package validation
fn local_name(name: &[u8]) -> &[u8] {
match name.iter().rposition(|&b| b == b':') {
Some(i) => name.get(i + 1..).unwrap_or(name),
None => name,
}
fn local_name(name: &str) -> &str {
name.rsplit(':').next().unwrap_or(name)
}
/// `(element local name, attributes)` for every start/empty element of an XML part.
@@ -41,12 +38,12 @@ fn xml_elements(xml: &[u8]) -> Result<Vec<XmlElement>, String> {
.map(|a| {
let v = match a.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
Ok(v) => v.into_owned(),
Err(_) => String::from_utf8_lossy(&a.value).into_owned(),
Err(_) => a.value.to_string(),
};
(String::from_utf8_lossy(local_name(a.key.as_ref())).into_owned(), v)
(local_name(a.key.as_ref()).to_string(), v)
})
.collect();
out.push((String::from_utf8_lossy(local_name(e.name().as_ref())).into_owned(), attrs));
out.push((local_name(e.name().as_ref()).to_string(), attrs));
}
Ok(Event::Eof) => break,
Ok(_) => {}
@@ -110,12 +107,20 @@ fn resolve_target(source_dir: &str, target: &str) -> String {
type Zip<'a> = zip::ZipArchive<Cursor<&'a [u8]>>;
fn zip_names(zip: &mut Zip<'_>) -> Vec<String> {
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| f.name().to_string())).collect()
/// `(index, name)` of every file entry. Parts are read by index: two entries can decode to the
/// same name, and looking up a CP437 name scans the whole archive.
fn zip_names(zip: &mut Zip<'_>) -> Vec<(usize, String)> {
(0..zip.len().min(MAX_ENTRIES)).filter_map(|i| zip.by_index_raw(i).ok().filter(|f| !f.is_dir()).map(|f| (i, entry_name(&f)))).collect()
}
fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?;
/// An entry's name: UTF-8, or CP437 when the entry isn't flagged UTF-8. A name that doesn't decode
/// is listed with its raw bytes made lossy, so the entry is still checked and reported.
fn entry_name<R: std::io::Read>(f: &zip::read::ZipFile<'_, R>) -> String {
f.name().map(|n| n.into_owned()).unwrap_or_else(|_| String::from_utf8_lossy(f.name_raw()).into_owned())
}
fn read_zip_part(zip: &mut Zip<'_>, index: usize, name: &str) -> Result<Vec<u8>, String> {
let f = zip.by_index(index).map_err(|e| format!("{name}: {e}"))?;
let mut buf = Vec::new();
f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?;
Ok(buf)
@@ -128,8 +133,8 @@ enum PartError {
}
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_index(index).map_err(|_| PartError::Unreadable)?;
// One byte past what is left shows that the part doesn't fit.
let limit = MAX_XML_PART.min(budget.saturating_add(1));
let mut buf = Vec::new();
@@ -150,10 +155,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Resu
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
let Ok(mut zip) = zip::ZipArchive::new(Cursor::new(bytes)) else { return false };
let names = zip_names(&mut zip);
let find = |key: &str| names.iter().find(|n| part_key(n) == key).cloned();
let find = |key: &str| names.iter().find(|(_, n)| part_key(n) == key).cloned();
let mut workbook = "xl/workbook.xml".to_string();
if let Some(rels) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, &rels)
if let Some((i, rels)) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, i, &rels)
&& let Ok(els) = xml_elements(&xml)
&& let Some(target) = els
.iter()
@@ -162,8 +167,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
{
workbook = resolve_target("", target);
}
let Some(name) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, &name) else { return false };
let Some((i, name)) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false };
xml_elements(&xml)
.ok()
.into_iter()
@@ -177,15 +182,15 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let parts: HashSet<String> = names.iter().map(|n| part_key(n)).collect();
let mut read_part = |name: &str| read_zip_part(&mut zip, name);
let parts: HashSet<String> = names.iter().map(|(_, n)| part_key(n)).collect();
let mut read_part = |index: usize, name: &str| read_zip_part(&mut zip, index, name);
let mut issues = Vec::new();
let ct_name = names.iter().find(|n| part_key(n) == "[content_types].xml").cloned();
let ct_name = names.iter().find(|(_, n)| part_key(n) == "[content_types].xml").cloned();
let (mut defaults, mut overrides) = (HashSet::new(), HashSet::new());
match ct_name {
None => issues.push("no [Content_Types].xml".to_string()),
Some(n) => {
for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
Some((i, n)) => {
for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
match el.as_str() {
"Default" => {
if let Some(x) = attr(&attrs, "Extension") {
@@ -202,9 +207,9 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
}
}
}
let mut sorted: Vec<&String> = names.iter().collect();
sorted.sort();
for n in &sorted {
let mut sorted: Vec<&(usize, String)> = names.iter().collect();
sorted.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
for (_, n) in &sorted {
let key = part_key(n);
if key == "[content_types].xml" {
continue;
@@ -219,7 +224,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
for p in missing_overrides {
issues.push(format!("content type override for missing part /{p}"));
}
for n in sorted {
for (i, n) in sorted {
let key = part_key(n);
let Some(rels_file) = key.strip_suffix(".rels") else { continue };
// `dir/_rels/name.rels` describes `dir/name`; `_rels/.rels` the package itself.
@@ -233,7 +238,7 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
issues.push(format!("{n} describes missing part {source}"));
}
let mut ids = HashSet::new();
for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? {
for (el, attrs) in xml_elements(&read_part(*i, n)?).map_err(|e| format!("{n}: {e}"))? {
if el != "Relationship" {
continue;
}
@@ -268,17 +273,17 @@ pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
let by_key: HashMap<String, &(usize, String)> = names.iter().map(|e| (part_key(&e.1), e)).collect();
// Several relationships name the same part; each fresh check decompressed it again, so
// repeated references to one highly compressible part multiplied the work. The verdict is
// remembered per (part, named content) and the decompression the package can cause is
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
// would otherwise each spend a full per-part allowance.
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
let mut verdicts: HashMap<(usize, &'static str), bool> = HashMap::new();
let mut kinds = BTreeMap::new();
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) {
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
let xml = match read_zip_part_within(&mut zip, *i, &mut budget) {
Ok(xml) => xml,
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
Err(PartError::Unreadable) => continue,
@@ -292,8 +297,8 @@ fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<S
}
let external = attr(attrs, "TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("External"));
if !external
&& let Some(part) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, part, kind, &mut verdicts, &mut budget)
&& let Some((index, _)) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, *index, kind, &mut verdicts, &mut budget)
{
continue;
}
@@ -314,7 +319,7 @@ fn rels_source_dir(key: &str) -> Option<String> {
/// comes first) a comment, for VML a shape. Read only as far as needed; an unreadable part counts.
/// `verdicts` remembers the answer per (part, named content); `budget` is the decompression this
/// package's remaining checks may cause, and once it is spent the part counts as having content.
fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'static str), bool>, budget: &mut u64) -> bool {
fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool {
let wanted: Option<&'static [u8]> = match kind.to_ascii_lowercase().as_str() {
"comments" => Some(b"comment"),
"vmldrawing" => Some(b"shape"),
@@ -325,26 +330,26 @@ fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut Has
Some(_) => "shape",
None => "any",
};
if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) {
if let Some(v) = verdicts.get(&(index, marker)) {
return *v;
}
let v = holds_something_uncached(zip, name, marker, budget);
verdicts.insert((name.to_ascii_lowercase(), marker), v);
let v = holds_something_uncached(zip, index, marker, budget);
verdicts.insert((index, marker), v);
v
}
fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool {
fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool {
use quick_xml::events::Event;
let Ok(f) = zip.by_name(name) else { return true };
let Ok(f) = zip.by_index(index) else { return true };
if *budget == 0 {
return true;
}
let take = f.size().min(MAX_XML_PART).min(*budget);
*budget -= take;
let mut reader = quick_xml::Reader::from_reader(std::io::BufReader::new(f.take(take)));
let wanted: Option<&'static [u8]> = match marker {
"comment" => Some(b"comment"),
"shape" => Some(b"shape"),
let wanted: Option<&'static str> = match marker {
"comment" => Some("comment"),
"shape" => Some("shape"),
_ => None,
};
let mut buf = Vec::new();
@@ -392,6 +397,57 @@ mod tests {
z.finish().unwrap().into_inner()
}
/// A package with two relationship parts whose names both read `xl/_rels/é.xml.rels`: the first
/// stored as UTF-8 holding `first`, the second stored as CP437 (byte 0x82) holding `second`.
fn same_name_rels(first: &str, second: &str) -> Vec<u8> {
const PLACEHOLDER: &[u8] = b"xl/_rels/Q.xml.rels";
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
z.start_file("xl/_rels/\u{e9}.xml.rels", opts).unwrap();
z.write_all(first.as_bytes()).unwrap();
z.start_file(String::from_utf8(PLACEHOLDER.to_vec()).unwrap(), opts).unwrap();
z.write_all(second.as_bytes()).unwrap();
let mut bytes = z.finish().unwrap().into_inner();
// The name sits in the local header and in the central directory; both get the CP437 byte.
let mut at = 0;
let mut patched = 0;
while let Some(i) = bytes.get(at..).and_then(|rest| rest.windows(PLACEHOLDER.len()).position(|w| w == PLACEHOLDER)) {
bytes[at + i + 9] = 0x82;
at += i + PLACEHOLDER.len();
patched += 1;
}
assert_eq!(patched, 2);
bytes
}
fn rels_xml(rels: &[(&str, &str)]) -> String {
let body: String = rels
.iter()
.map(|(id, kind)| {
format!(
r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}" Target="https://example.com" TargetMode="External"/>"#
)
})
.collect();
format!(r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{body}</Relationships>"#)
}
#[test]
fn parts_with_the_same_decoded_name_are_each_validated() {
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "custom"), ("rId1", "custom")]));
let issues = validate_package(&bytes).unwrap();
let duplicates = issues.iter().filter(|i| i.ends_with("duplicate relationship id rId1")).count();
assert_eq!(duplicates, 1, "{issues:?}");
}
#[test]
fn relationship_kinds_read_parts_with_the_same_decoded_name() {
let bytes = same_name_rels(&rels_xml(&[("rId1", "custom")]), &rels_xml(&[("rId1", "audio")]));
let kinds = relationship_kinds(&bytes).unwrap();
assert!(kinds.contains_key("custom"), "{kinds:?}");
assert!(kinds.contains_key("audio"), "{kinds:?}");
}
#[test]
fn relationship_parts_count_against_the_decompression_budget() {
// Each part fits the per-part allowance, but together they need more than the budget.
+1 -1
View File
@@ -344,7 +344,7 @@ fn with_rels(bytes: &[u8], rels: &[(&str, &str)], parts: &[(&str, &str)]) -> Vec
let mut pending: Vec<(&str, &str)> = rels.to_vec();
for i in 0..src.len() {
let mut f = src.by_index(i).unwrap();
let name = f.name().to_string();
let name = f.name().unwrap().to_string();
let mut body = String::new();
f.read_to_string(&mut body).unwrap();
if let Some(at) = pending.iter().position(|(r, _)| *r == name) {
+43 -1
View File
@@ -65,12 +65,35 @@ fn stdout_failed(e: std::io::Error) -> ! {
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) {
@@ -164,7 +187,7 @@ impl Args {
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 id == "file.open"
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)
{
@@ -305,6 +328,9 @@ fn convert(args: &[String]) -> Result<(), String> {
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())?;
@@ -590,6 +616,22 @@ 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"}))));
+4 -3
View File
@@ -18,16 +18,17 @@ gridcraft-engine = { workspace = true }
gridcraft-ui-egui = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.gridcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
craft-print = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
+4 -70
View File
@@ -49,6 +49,7 @@ pub fn start() {
canvas,
options,
Box::new(move |cc| {
gridcraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let inbox: Inbox = Inbox::default();
let mut session = Session::new();
// In host mode the host sends the workbook to edit; no sample meanwhile.
@@ -158,6 +159,7 @@ impl eframe::App for WebShell {
});
}
self.app.logic(ctx);
self.app.close_path(ctx);
// Store changed preferences straight away: a reload or closed tab runs no exit code (#1562).
let changed = self.prefs.changed(&self.app);
if !changed.is_empty() {
@@ -177,6 +179,7 @@ impl eframe::App for WebShell {
/// Forwards a browser frame's raw input to the shared app before eframe handles it.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
@@ -225,7 +228,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
}
})),
print: Some(Box::new(|bytes: &[u8]| {
if let Err(e) = print_pdf(bytes) {
if let Err(e) = craft_print::browser::print_pdf(bytes) {
log::error!("print failed: {e}");
}
})),
@@ -277,75 +280,6 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
Ok(())
}
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
/// `print()` once it has finished loading — the standard way to drive the browser's native print
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
/// them.
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let window = web_sys::window().ok_or("no window")?;
let document = window.document().ok_or("no document")?;
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
iframe.style().set_property("display", "none").map_err(js)?;
let body = document.body().ok_or("no body")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
let opts = web_sys::BlobPropertyBag::new();
opts.set_type("application/pdf");
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
if let Err(e) = body.append_child(&iframe) {
cleanup_print(&iframe, &url);
return Err(js(e));
}
// `onload` fires once the PDF has actually rendered inside the iframe;
// printing before that would show a blank page. Set the handler BEFORE
// `src` so a fast/cached load can't fire before we're listening.
let iframe_for_load = iframe.clone();
let url_for_cleanup = url.clone();
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
iframe_for_load.set_onload(None);
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
cleanup_print(&iframe_for_load, &url_for_cleanup);
log::error!("print failed: {e:?}");
}
});
iframe.set_onload(Some(on_load.unchecked_ref()));
iframe.set_src(&url);
Ok(())
}
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
// Both operations are idempotent: print can fail after dispatching `afterprint`.
web_sys::Url::revoke_object_url(url).ok();
iframe.remove();
}
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
let iframe_for_cleanup = iframe.clone();
let url_for_cleanup = url.to_owned();
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
});
// Listen before `print()`, which can dispatch `afterprint` before it returns.
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
let options = web_sys::AddEventListenerOptions::new();
options.set_once(true);
let callback = on_after_print.as_ref().unchecked_ref();
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
if let Err(e) = content_window.print() {
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
return Err(e);
}
let _ = on_after_print.into_js_value();
Ok(())
}
fn mime_for(name: &str) -> &'static str {
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+9 -1
View File
@@ -30,9 +30,11 @@ winresource = "0.1"
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Nightly self-isolation, launch protocol, and security fence (storytold/craft-libs).
craft-nightly = { workspace = true }
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
# Cargo.toml).
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
craft-print = { workspace = true }
craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
@@ -43,9 +45,15 @@ getrandom = "0.4"
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
arboard = { workspace = true, features = ["image-data", "wayland-data-control"] }
# GNOME does not provide server-side decorations on Wayland. Keep the Adwaita frame
# and buttons without embedding its fallback title font; the ribbon shows the name (#54).
winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
[target.'cfg(target_os = "windows")'.dependencies]
# Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe.
pollster = "1"
# The explicit AppUserModelID the nightly channel sets before its first window (`process_identity.rs`).
winsafe = { version = "0.0.29", features = ["user", "shell"] }
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
+48 -6
View File
@@ -1,25 +1,67 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `gridcraft.exe`, so it
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1` turns it
//! into an error (for release builds).
//! On every other target this does nothing but the channel work. A missing resource compiler is a
//! warning, so a cross-compile from macOS or Linux still links, unless `GRIDCRAFT_REQUIRE_WINRES=1`
//! turns it into an error (for release builds).
//!
//! The nightly channel is a build-time decision: `GRIDCRAFT_BUILD_CHANNEL=nightly-v1` sets
//! `cfg(gridcraft_nightly_v1)` and requires the prepared `GRIDCRAFT_VERSION` feed identity, which
//! becomes the executable's `ProductVersion` (the Launcher checks that, not `FileVersion`) and the
//! version the app answers `--version` with. Anything else than `stable`, empty or `nightly-v1`
//! is a build error, so a typo cannot silently ship the wrong channel.
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_BUILD_CHANNEL");
println!("cargo:rustc-check-cfg=cfg(gridcraft_nightly_v1)");
let nightly = match std::env::var("GRIDCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=gridcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported GRIDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/gridcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=GRIDCRAFT_VERSION");
let built_version = if nightly {
match std::env::var("GRIDCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit GRIDCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=GRIDCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/gridcraft.ico")
.set("ProductName", "GridCraft")
.set("FileDescription", "GridCraft spreadsheet")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "GridCraft Nightly" } else { "GridCraft" })
.set("FileDescription", if nightly { "GridCraft Nightly spreadsheet" } else { "GridCraft spreadsheet" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the GridCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "gridcraft.exe")
.set("InternalName", "gridcraft");
if nightly {
// The Launcher compares the PE ProductVersion with the exact feed identity.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("GRIDCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
+92
View File
@@ -0,0 +1,92 @@
//! The one place a GridCraft data root is resolved, so the nightly profile and the platform
//! default can never disagree.
//!
//! Everything the desktop writes about the user lives under [`config_dir`]: `ui.json`,
//! `prefs.json` and `logs/` (see `logging`). The control channel's token folder is resolved by
//! `gridcraft_mcp` from the same root at start-up. Nothing else in the app persists user state.
//! A nightly takes its root from the Launcher's validated profile and nothing else, so stable has
//! no environment override of its own: the platform's published folder is the whole story.
use std::ffi::OsString;
use std::path::PathBuf;
fn default_config_dir(platform: &str, env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
match platform {
"macos" => env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/GridCraft")),
"windows" => env("APPDATA").map(|a| PathBuf::from(a).join("GridCraft")),
_ => env("XDG_CONFIG_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft")),
}
}
/// The folder the settings and the log files live in.
pub fn config_dir_for(platform: &str, env: &impl Fn(&str) -> Option<OsString>, nightly_root: Option<&std::path::Path>) -> Option<PathBuf> {
match nightly_root {
// The profile was already validated (absolute, fenced, writable) before this runs.
Some(root) => Some(root.to_path_buf()),
None => default_config_dir(platform, env),
}
}
pub fn config_dir() -> Option<PathBuf> {
config_dir_for(std::env::consts::OS, &|key| std::env::var_os(key), crate::launch_profile::current().root())
}
/// Where the log files live: `logs` in the settings folder, next to `ui.json`.
pub fn log_dir() -> Option<PathBuf> {
Some(config_dir()?.join("logs"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<OsString> {
let map: BTreeMap<String, OsString> = pairs.iter().map(|(k, v)| ((*k).to_string(), OsString::from(v))).collect();
move |key| map.get(key).cloned()
}
#[test]
fn each_platform_keeps_its_published_folder() {
// The base is joined with the host's own separator, so these hold on any machine the gate
// runs on: what each platform publishes is the folder name, not how the host spells a slash.
let appdata = PathBuf::from(r"C:\Users\u\AppData\Roaming");
assert_eq!(config_dir_for("windows", &env(&[("APPDATA", &appdata.to_string_lossy())]), None), Some(appdata.join("GridCraft")));
let home = PathBuf::from("/home/u");
assert_eq!(
config_dir_for("macos", &env(&[("HOME", &home.to_string_lossy())]), None),
Some(home.join("Library/Application Support/GridCraft"))
);
assert_eq!(config_dir_for("linux", &env(&[("HOME", &home.to_string_lossy())]), None), Some(home.join(".config").join("gridcraft")));
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home.to_string_lossy())]), None),
Some(PathBuf::from("/xdg").join("gridcraft"))
);
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "")]), None), None);
}
#[test]
fn an_empty_xdg_config_home_falls_back_to_the_home_folder() {
let home = PathBuf::from("/home/u");
let home_str = home.to_string_lossy().into_owned();
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", ""), ("HOME", &home_str)]), None),
Some(home.join(".config").join("gridcraft"))
);
assert_eq!(
config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", &home_str)]), None),
Some(PathBuf::from("/xdg").join("gridcraft"))
);
}
#[test]
fn the_nightly_profile_is_the_whole_answer() {
let profile = std::path::Path::new("/var/lib/gridcraft-nightly/profile");
assert_eq!(config_dir_for("linux", &env(&[("XDG_CONFIG_HOME", "/xdg"), ("HOME", "/home/u")]), Some(profile)), Some(profile.to_path_buf()));
assert_eq!(config_dir_for("linux", &env(&[("HOME", "/home/u")]), Some(profile)).unwrap().join("logs"), profile.join("logs"));
}
}
+55
View File
@@ -0,0 +1,55 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/gridcraft-nightly.ico" } else { "../../assets/app-icon/gridcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/gridcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/gridcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.19.1-nightly.20261124.7.1.gabcdef012345"));
for invalid in [
"",
"0.19.1",
"0.19.1-nightly",
"0.19.1-nightly.20261124",
"0.19.1-nightly.20261124.7.1.gABCDEF012345",
"0.19.1-nightly.20261124.7.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.19.1-nightly.20261124.1.1.gabcdef012345",
"0.19.1-nightly.20261124.1.1.gabcdef012345/other",
"0.19.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+46
View File
@@ -0,0 +1,46 @@
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
//! stable build, and a nightly build always stays isolated in its nightly profile.
use std::ffi::OsString;
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::{BuildFlavor, needs_native_error, version, version_query};
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.19.1"), "0.19.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+135
View File
@@ -0,0 +1,135 @@
//! Nightly-v1 bootstrap backed by `craft-nightly`, selected before logging, updates, fonts or saved
//! state. Direct launches of a nightly build self-isolate into
//! `craft_nightly::canonical_profile_root("gridcraft")`, while ArtCraft Launcher may still pass
//! `--launch-profile nightly-v1 --profile-root <absolute> -- <files...>`. Stable launches keep
//! their original arguments and directory policy.
use std::ffi::OsString;
pub use craft_nightly::Profile;
/// Returns the process-wide profile installed by `craft_nightly::prepare_launch`, defaulting to
/// [`Profile::Stable`] before startup selection.
pub fn current() -> &'static Profile {
craft_nightly::current().unwrap_or(&Profile::Stable)
}
/// Restores the `--` option terminator when `craft_nightly::parse_startup` consumed it after an
/// explicit `--launch-profile` / `--profile-root` header, so downstream argument parsing keeps
/// treating every launcher-supplied tail token (such as a file named `--control`) as a filename.
pub fn restore_launcher_separator(raw_args: &[OsString], passthrough_args: Vec<OsString>) -> Vec<OsString> {
let separator_index = raw_args.len().checked_sub(passthrough_args.len() + 1);
if let Some(index) = separator_index
&& raw_args.get(index).is_some_and(|arg| arg == "--")
{
return std::iter::once(OsString::from("--")).chain(passthrough_args).collect();
}
passthrough_args
}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use craft_nightly::{
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup,
};
use super::restore_launcher_separator;
use crate::profile_root;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
}
fn nightly() -> Vec<OsString> {
launch_arguments(Path::new(absolute()), &[])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = profile_root::app_spec();
for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
}
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
let spec = profile_root::app_spec();
let expected_root = canonical_profile_root("gridcraft").expect("canonical root");
let argv = args(&["sales.xlsx", "--sample", "budget"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
}
#[test]
fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() {
let spec = profile_root::app_spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(
restore_launcher_separator(&argv, launch.passthrough_args),
args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])
);
}
#[test]
fn stable_build_refuses_nightly_launch_flags() {
let spec = profile_root::app_spec();
let result = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::default());
assert!(matches!(result, Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
let spec = profile_root::app_spec();
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "sales.xlsx", "--profile-root", absolute()]),
args(&["sales.xlsx", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
] {
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).is_err(), "{argv:?}");
}
}
#[test]
fn launcher_version_queries_are_recognized_without_touching_the_profile() {
let spec = profile_root::app_spec();
for argv in [
args(&["--version"]),
args(&["-V"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
launch_arguments(Path::new(absolute()), &args(&["--version"])),
launch_arguments(Path::new(absolute()), &args(&["-V"])),
] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
assert!(launch.is_version_query(), "{argv:?}");
}
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--help"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--control", "7979", "--version"]),
launch_arguments(Path::new(absolute()), &args(&["sales.xlsx", "--version"])),
] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
assert!(!launch.is_version_query(), "{argv:?}");
}
}
}
+357 -73
View File
@@ -9,16 +9,25 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod app_dirs;
#[cfg(target_os = "macos")]
mod apple_events;
// The build channel's own parser and icon-path tests (build.rs compiles the same file by path).
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
#[cfg(any(target_os = "windows", target_os = "macos", test))]
mod graphics;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod opener;
mod print;
mod process_identity;
mod profile_root;
use std::cell::RefCell;
use std::rc::Rc;
@@ -29,45 +38,63 @@ use gridcraft_ui_egui::{Services, SheetApp};
use serde_json::json;
/// The app, its native window per workbook window, and (macOS) the menu bar and Finder events.
struct App(SheetApp, DocWindows, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>, #[cfg(target_os = "macos")] fmv_macos_events::Inbox);
/// The session record and its notice flag are only meaningful in the nightly channel.
struct App {
app: SheetApp,
windows: DocWindows,
#[cfg(target_os = "macos")]
menu: Option<native_menu::NativeMenu>,
#[cfg(target_os = "macos")]
apple_events: fmv_macos_events::Inbox,
/// The Nightly session record, shared with the exit hook and the return path.
nightly: nightly_session::Shared,
/// Whether this window already told the user the previous session did not finish.
nightly_notice_shown: bool,
}
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
{
if self.2.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
self.2 = Some(native_menu::NativeMenu::install(ctx));
if self.menu.is_none() && std::env::var_os("GRIDCRAFT_NO_NATIVE_MENU").is_none() {
self.menu = Some(native_menu::NativeMenu::install(ctx));
}
if let Some(m) = &mut self.2 {
m.poll(&mut self.0, ctx, self.1.focused_viewport());
if let Some(m) = &mut self.menu {
m.poll(&mut self.app, ctx, self.windows.focused_viewport());
}
apple_events::poll(&self.3, &mut self.0, ctx);
}
self.0.logic(ctx);
self.1.logic(&mut self.0, ctx);
if ctx.input(|input| input.viewport().close_requested()) && self.0.printing.busy() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
apple_events::poll(&self.apple_events, &mut self.app, ctx);
}
self.app.logic(ctx);
self.windows.logic(&mut self.app, ctx);
self.app.close_path(ctx);
}
/// Forwards raw input to the shared app, then opens every non-empty dropped file path as a workbook.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.0.raw_input_hook(ctx, raw);
self.app.raw_input_hook(ctx, raw);
self.app.before_input(ctx);
// Files dropped on the window open as workbooks.
for f in std::mem::take(&mut raw.dropped_files) {
if let Some(p) = f.path().to_str().map(str::to_string).filter(|p| !p.is_empty()) {
self.0.open_path(&p);
self.app.open_path(&p);
}
}
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.1.show(&mut self.0, ui);
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.windows.show(&mut self.app, ui);
}
fn on_exit(&mut self) {
print::finish_pending_jobs();
save_prefs(&self.0);
save_prefs(&self.app);
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here.
self.0.start_pending_update();
// dropping the app, so the helper is started here. A nightly has no updater at all.
if gridcraft_ui_egui::channel::stable_services_allowed() {
self.app.start_pending_update();
}
// The Nightly session record is finished here: every way of quitting reaches `on_exit`,
// and on macOS AppKit's terminate ends the process right after it, so nothing after
// `eframe::run_native` can run there. `finish_once` makes the later call a no-op.
nightly_session::finish_once(&self.nightly, self.nightly_notice_shown);
// macOS (#117): end the process here, before eframe tears the window down. AccessKit's
// macOS adapter subclasses the window's content view and restores its class on teardown;
// AppKit's Touch Bar support observes that view (KVO), so in the next display cycle
@@ -81,17 +108,10 @@ impl eframe::App for App {
}
}
/// The settings folder: the validated nightly profile, else the platform's own folder
/// (`app_dirs`). Every writer of user state goes through it.
fn config_dir() -> Option<std::path::PathBuf> {
if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/GridCraft"))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("GridCraft"))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join("gridcraft"))
}
app_dirs::config_dir()
}
/// Runs without preferences (`GRIDCRAFT_NO_PREFS`, agents' test runs) neither read nor write
@@ -102,7 +122,7 @@ fn prefs_enabled() -> bool {
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
fn log_dir() -> Option<std::path::PathBuf> {
Some(config_dir()?.join("logs"))
app_dirs::log_dir()
}
fn load_prefs(app: &mut SheetApp) {
@@ -194,8 +214,13 @@ fn services() -> Services {
let path = std::path::Path::new(suggested);
let stem = path.file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("Book1").to_string();
// The suggested name's type (an export asks for .pdf, .csv or .html) comes first.
const TYPES: [(&str, &str); 4] =
[("Excel Workbook (.xlsx)", "xlsx"), ("CSV UTF-8 (.csv)", "csv"), ("Web Page (.html)", "html"), ("PDF (.pdf)", "pdf")];
const TYPES: [(&str, &str); 5] = [
("Excel Workbook (.xlsx)", "xlsx"),
("CSV UTF-8 (.csv)", "csv"),
("Web Page (.html)", "html"),
("PDF (.pdf)", "pdf"),
("GridCraft Workbook (.json)", "json"),
];
let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).filter(|e| TYPES.iter().any(|(_, x)| x == e));
let ext = ext.unwrap_or_else(|| "xlsx".to_string());
let mut dialog = rfd::FileDialog::new().set_file_name(format!("{stem}.{ext}"));
@@ -241,13 +266,156 @@ fn icon() -> Option<egui::IconData> {
Some(egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() })
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
gridcraft_ui_egui::channel::id_for(gridcraft_ui_egui::channel::Channel::NightlyV1),
)
}
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// Tell a desktop user why a nightly launch was refused, in a native box where one renders without the
/// app's event loop (Windows, X11/Wayland), and on standard error always. A headless form (`--version`
/// on a runner) never gets here: the version query is answered before this and before any profile work.
fn report_launch_profile_error(error: &str) {
eprintln!("GridCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("GridCraft launch profile: {error}");
return;
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
let _ = rfd::MessageDialog::new()
.set_title("GridCraft Nightly")
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch channel and profile before any startup service or side effect.
/// `None` means the answer was printed (`--version`) and the process is done.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
// Plain `--version` / `-V` on a nightly build is answered before any profile resolution,
// process identity, IPC, or window (a dialog here would hang a headless runner and fail a
// Linux build, and `--version` must still work when HOME / LOCALAPPDATA is unset).
if nightly_build && build_flavor::version_query(&argv) {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
return None;
}
let spec = profile_root::app_spec();
let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv.iter().cloned(), &craft_nightly::StartupOptions::default())
.unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
// `craft_nightly::prepare_launch` performs no filesystem preparation and installs no profile.
if nightly_build && launch.is_version_query() {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let channel =
if launch.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) = gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(launch_profile::restore_launcher_separator(&argv, launch.passthrough_args))
}
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
/// documents (`launch_profile::restore_launcher_separator` preserves the separator first), so the
/// separator itself is never opened as a file.
#[derive(Debug, Default, PartialEq)]
struct DesktopArgs {
control_port: Option<u16>,
control_token: Option<String>,
sample: Option<String>,
files: Vec<String>,
}
fn desktop_args(args: &[String], control_port: Option<u16>, control_token: Option<String>) -> DesktopArgs {
let mut parsed = DesktopArgs { control_port, control_token, ..DesktopArgs::default() };
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--" => {
parsed.files.extend(args[i + 1..].iter().cloned());
break;
}
"--control" => {
i += 1;
parsed.control_port = args.get(i).and_then(|p| p.parse().ok());
}
"--control-token" => {
i += 1;
parsed.control_token = args.get(i).cloned();
}
"--sample" => {
i += 1;
parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
}
a if a.starts_with("-psn_") => {}
a => parsed.files.push(a.to_string()),
}
i += 1;
}
parsed
}
/// A nightly owns no control channel, and only options count: everything after `--` is a file, so a
/// document named `--control` is opened rather than read as a flag.
fn nightly_control_refused(nightly: bool, args: &[String]) -> bool {
let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len());
nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token")
}
fn main() -> eframe::Result<()> {
// A confined launcher run (`gridcraft_sandbox::launch_command`) comes before everything else:
// it opens no window, writes no log, and becomes the program it confines.
// A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from
// this same executable) comes before everything else: it opens no window, writes no log, and
// becomes the program it confines. It must stay ahead of the launch profile, or a nightly build
// would refuse its own sandbox helper.
let raw: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
if let Some(code) = gridcraft_sandbox::handle_args(&raw) {
std::process::exit(code);
}
// Then the Launcher protocol and the version query (see `prepare_launch`).
let Some(arguments) = prepare_launch() else { return Ok(()) };
// A nightly profile owns its control tokens as well, so even a nightly build that is asked
// for a control server can never write the stable app's token file.
if let Some(root) = launch_profile::current().root() {
match profile_root::control_directory(root).and_then(gridcraft_mcp::control_auth::set_token_root) {
Ok(()) => {}
Err(error) => {
report_launch_profile_error(&error);
std::process::exit(2);
}
}
}
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
// Commands catch their panics (`Session::execute`), but the default hook only prints to
@@ -268,43 +436,34 @@ fn main() -> eframe::Result<()> {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("gridcraft: {report}\n"));
}
}));
let args: Vec<String> = std::env::args().skip(1).collect();
let args: Vec<String> = arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect();
let nightly = gridcraft_ui_egui::channel::current() == gridcraft_ui_egui::channel::Channel::NightlyV1;
// The restart helper a self-update spawns: it finishes the swap and relaunches, then exits.
if let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
// A nightly has no updater, so it never runs this and never inherits a stable swap.
if !nightly
&& let Some(done) = craft_update::self_update::finish(&gridcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
if let Err(e) = done {
eprintln!("GridCraft update helper failed: {e}");
std::process::exit(1);
}
return Ok(());
}
if args.iter().any(|a| a == "--version" || a == "-V") {
println!("GridCraft {}", env!("CARGO_PKG_VERSION"));
// Before `--` only: everything after it is a file, even one named `--version`.
if arguments.iter().take_while(|a| *a != "--").any(|a| a == "--version" || a == "-V") {
println!("GridCraft {}", gridcraft_ui_egui::channel::version());
return Ok(());
}
let mut control_port: Option<u16> = std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut control_token: Option<String> = std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok();
let mut sample: Option<String> = None;
let mut files: Vec<String> = Vec::new();
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--control" => {
i += 1;
control_port = args.get(i).and_then(|p| p.parse().ok());
}
"--control-token" => {
i += 1;
control_token = args.get(i).cloned();
}
"--sample" => {
i += 1;
sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into()));
}
a if a.starts_with("-psn_") => {}
a => files.push(a.to_string()),
}
i += 1;
// The control channel is a stable-only service: a nightly window owns no port, writes no
// token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`.
if nightly_control_refused(nightly, &args) {
eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel");
std::process::exit(2);
}
let control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
let control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
let parsed = desktop_args(&args, control_port, control_token);
let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files);
// The log file lives in the settings folder, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
@@ -312,7 +471,9 @@ fn main() -> eframe::Result<()> {
if let Some(logger) = logger {
match log_dir().filter(|_| prefs_enabled()) {
Some(dir) => match logger.attach_dir(&dir) {
Ok(path) => log::info!("GridCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()),
Ok(path) => {
log::info!("{} {}, log file {}", gridcraft_ui_egui::channel::name(), gridcraft_ui_egui::channel::version(), path.display())
}
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
Err(e) => log::warn!("no log file: {e}"),
},
@@ -327,14 +488,41 @@ fn main() -> eframe::Result<()> {
}
let mut app = SheetApp::new(session, services());
app.watch_desktop_theme();
app.start_update_check();
let control_port = control_port;
// The updater is a stable-only service: a nightly is installed, replaced and updated by the
// Launcher, so it never checks for one, never prompts and never writes craft-update's state.
if !nightly {
app.start_update_check();
}
load_prefs(&mut app);
// Stamp the startup workbook's author from the persisted user name.
if app.session.documents().is_empty() {
app.session.new_workbook();
}
app.after_engine(); // Show warnings from the sample.
// Nightly session health: the record is written before the window exists and finished by
// `on_exit`. A record left by an interrupted run is reported once, then cleared on the next
// clean quit.
let session_watch = std::sync::Arc::new(std::sync::Mutex::new(None));
let mut nightly_notice_shown = false;
match nightly_session::Session::begin_with_health(launch_profile::current().root(), env!("GRIDCRAFT_BUILT_VERSION")) {
Ok((watch, unavailable)) => {
if let Some(watch) = &watch
&& watch.previous_unclean()
{
app.notice = Some(gridcraft_ui_egui::Notice {
text: "The last GridCraft Nightly session did not finish cleanly. Your saved workbooks are as you left them; only unsaved changes are affected.".into(),
kind: gridcraft_ui_egui::NoticeKind::Warning,
action: None,
});
nightly_notice_shown = true;
}
if unavailable {
log::warn!("this window shares a GridCraft Nightly profile another window owns; its exit is not recorded");
}
*session_watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = watch;
}
Err(error) => log::warn!("Nightly session state was not written: {error}"),
}
// Files named on the command line (a double-click on Windows and Linux) open as File › Open
// opens them: a password-protected one asks for its password, and errors are shown, not
// only logged. Each replaces the untouched blank Book1, as a file opened from Finder does.
@@ -344,11 +532,16 @@ fn main() -> eframe::Result<()> {
// Linux/BSD: Excel's layout — no window-manager title bar above ours; our title bar carries the
// window controls. `GRIDCRAFT_SYSTEM_TITLEBAR=1` keeps the system frame.
app.window_controls = cfg!(not(any(target_os = "macos", target_os = "windows"))) && std::env::var_os("GRIDCRAFT_SYSTEM_TITLEBAR").is_none();
// The window carries its channel's name and OS app id: a nightly window is never mistaken for
// the stable one by a dock, a window manager rule or the taskbar (Windows AUMID above). A
// Flatpak package carries its own id instead, which is what its .desktop file and portal name.
let window_app_id =
std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| gridcraft_ui_egui::channel::app_id().to_string());
let mut viewport = egui::ViewportBuilder::default()
.with_title("GridCraft")
.with_title(gridcraft_ui_egui::channel::default_title())
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([640.0, 420.0])
.with_app_id("ai.storyteller.gridcraft")
.with_app_id(window_app_id)
.with_drag_and_drop(true)
.with_decorations(!app.window_controls);
if cfg!(target_os = "macos") {
@@ -387,12 +580,13 @@ fn main() -> eframe::Result<()> {
let pending = std::cell::Cell::new(Some(app));
let run = |options: eframe::NativeOptions| {
eframe::run_native(
"GridCraft",
gridcraft_ui_egui::channel::name(),
options,
Box::new(|cc| {
let Some(mut app) = pending.take() else {
return Err("the app was already created".into());
};
gridcraft_ui_egui::framework::install(&cc.egui_ctx)?;
SheetApp::setup_context_for_language(&cc.egui_ctx, app.ui.dark, app.ui.language);
if let Some(port) = control_port {
match control_server::start(port, control_token.clone(), cc.egui_ctx.clone()) {
@@ -401,14 +595,16 @@ fn main() -> eframe::Result<()> {
}
}
let windows = DocWindows::new(&mut app, window_builder.clone(), DocWindows::platform_quits_with_last_window());
Ok(Box::new(App(
Ok(Box::new(App {
app,
windows,
#[cfg(target_os = "macos")]
None,
menu: None,
#[cfg(target_os = "macos")]
apple_events.connect(&cc.egui_ctx),
)))
apple_events: apple_events.connect(&cc.egui_ctx),
nightly: session_watch.clone(),
nightly_notice_shown,
}))
}),
)
};
@@ -416,7 +612,7 @@ fn main() -> eframe::Result<()> {
// A graphics error before the app existed: start once more with the other backend (eframe
// reuses its event loop for the second run). Errors after that, or from winit, are returned.
#[cfg(target_os = "windows")]
if let Err(eframe::Error::Wgpu(e)) = &result
let result = if let Err(eframe::Error::Wgpu(e)) = &result
&& let Some(app) = pending.take()
&& let Some(backends) = graphics::fallback_backends(backend_override, first_backends)
{
@@ -424,8 +620,14 @@ fn main() -> eframe::Result<()> {
pending.set(Some(app));
let mut options = retry_options;
graphics::configure_backends(&mut options, backends);
return run(options);
}
run(options)
} else {
result
};
// A start that failed before the app existed never reached `on_exit`, and on the platforms
// where the event loop returns this is also the end of a clean exit. `finish_once` makes the
// second of the two calls a no-op, so a successor's record is never touched.
nightly_session::finish_once(&session_watch, nightly_notice_shown);
result
}
@@ -457,3 +659,85 @@ mod packaging_tests {
}
}
}
#[cfg(test)]
mod launch_separator_tests {
use super::*;
use crate::build_flavor::BuildFlavor;
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
/// `craft_nightly::validate_and_prepare_root` refuses a root that is relative there, and a
/// POSIX path has no drive or UNC prefix, so it is not absolute on Windows - where CI runs
/// these tests too.
fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
}
/// The argv the Launcher starts a nightly with, extended by `tail`, as the start then reads it.
fn launcher_argv(tail: &[&str]) -> Vec<String> {
let mut argv: Vec<std::ffi::OsString> =
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
let launch = craft_nightly::parse_startup(
BuildFlavor::NightlyV1,
&profile_root::app_spec(),
argv.iter().cloned(),
&craft_nightly::StartupOptions::default(),
)
.unwrap();
launch_profile::restore_launcher_separator(&argv, launch.passthrough_args).iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_other_platforms_root_spelling_is_refused_as_relative() {
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
let result = craft_nightly::validate_and_prepare_root(std::path::Path::new(foreign), &profile_root::app_spec());
assert!(
matches!(result, Err(craft_nightly::ProfileError::RelativeProfileRoot(_))),
"a root that is not absolute on this platform must be refused"
);
}
#[test]
fn the_launchers_separator_is_never_a_file() {
let parsed = desktop_args(&launcher_argv(&[]), None, None);
assert_eq!(parsed, DesktopArgs::default(), "the separator must not reach the file list");
}
#[test]
fn files_after_the_separator_are_opened_in_order() {
assert_eq!(desktop_args(&launcher_argv(&["a.file"]), None, None).files, ["a.file"]);
let parsed = desktop_args(&launcher_argv(&["a.file", "--version", "--sample"]), None, None);
assert_eq!(parsed.files, ["a.file", "--version", "--sample"], "after -- every word is a file");
assert_eq!((parsed.sample, parsed.control_port), (None, None));
}
#[test]
fn a_control_flag_after_the_separator_is_a_file_not_a_refusal() {
let argv = launcher_argv(&["--control"]);
assert!(!nightly_control_refused(true, &argv), "a document named --control must open, not refuse");
let parsed = desktop_args(&argv, None, None);
assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()]));
}
#[test]
fn a_control_flag_before_the_separator_still_names_the_port() {
let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()];
assert!(nightly_control_refused(true, &with_file));
let parsed = desktop_args(&with_file, None, None);
assert_eq!((parsed.control_port, parsed.files), (Some(7979), vec!["a.file".to_string()]));
let plain = vec!["--control".to_string(), "7979".to_string()];
assert!(nightly_control_refused(true, &plain));
let parsed = desktop_args(&plain, None, None);
assert_eq!((parsed.control_port, parsed.files), (Some(7979), Vec::<String>::new()));
assert!(!nightly_control_refused(false, &plain), "the stable app keeps its control channel");
}
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+310
View File
@@ -0,0 +1,310 @@
//! App-private Nightly session health, not telemetry and not a Launcher protocol.
//!
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker: only the app's controlled return path does, and
//! on macOS that path is `on_exit` (a ⌘Q ends the process inside AppKit's terminate, after
//! `on_exit`, so nothing after `eframe::run_native` runs there).
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Replace `path` with `bytes` without following a link at the destination: the temporary file is
/// created exclusively beside it and renamed over it, so a planted link is replaced, not written
/// through. `gridcraft_engine::io::write_file` does the same for workbooks; the session record is
/// the app's own file and must not depend on the engine's script sandbox policy.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no file name"))?;
let mut tmp_name = std::ffi::OsString::from(".");
tmp_name.push(name);
tmp_name.push(".new");
let tmp = path.with_file_name(tmp_name);
match std::fs::remove_file(&tmp) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let write = (|| -> io::Result<()> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o600);
}
let mut file = options.open(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
std::fs::rename(&tmp, path)
})();
if write.is_err() {
let _ = std::fs::remove_file(&tmp);
}
write
}
/// The owner's session, shared by the app's exit hook and the return path.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage, while
/// Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable, or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
// The commit is read back from the version (`…g<sha12>`), never invented here.
let commit = gridcraft_ui_egui::channel::commit_for(version);
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit,
}))?;
atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed it
/// yet (a failed start before the app existed), the record is left for the next owner.
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Clear the record this owner wrote, and only that one. An unwind, abort, forced exit or killed
/// process never calls this.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("gridcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
fn version() -> &'static str {
"0.19.1-nightly.20261124.7.1.gabcdef012345"
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable").unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), version()).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), version()).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), version()).unwrap().unwrap());
// The renderer failed before the app existed: no notice was shown.
let failed = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), version()).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
let successor = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1)).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "").unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), version()).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["channel", "commit", "schema_version", "version"].into_iter().collect());
assert_eq!(data["commit"], "abcdef012345", "the commit comes from the version, not the environment");
watch.complete().unwrap();
}
#[test]
fn a_version_without_a_commit_does_not_invent_one() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "0.19.1").unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
assert!(data["commit"].is_null());
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), version()).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
#[test]
#[cfg(unix)]
fn replacing_a_planted_record_link_writes_our_own_file_only() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
std::os::unix::fs::symlink(&external, fixture.0.join(RECORD)).unwrap();
// regular_or_missing refuses an alias outright; the temporary writer is what a first write
// uses, and it never follows one either.
assert!(Session::begin(Some(&fixture.0), version()).is_err());
// The link is at RECORD itself: writing there must replace the alias, not follow it.
atomic_write_no_follow(&fixture.0.join(RECORD), b"ours").unwrap();
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"ours");
assert!(!fixture.0.join(RECORD).is_symlink(), "the alias must be replaced, not written through");
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
assert!(!fixture.0.join(".nightly-session.json.new").exists());
}
}
+12 -10
View File
@@ -1,15 +1,12 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Discover, Duplex, Printer, Settings, Submit};
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
/// Returns a printer-discovery closure that enumerates `craft_print::printers()` on a named background thread and sends the mapped list through a channel.
pub fn discover() -> Discover {
Box::new(|| {
let (sender, receiver) = std::sync::mpsc::channel();
let _ = std::thread::Builder::new().name("print-discovery".into()).spawn(move || {
let printers = craft_print::printers()
.into_iter()
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
.collect();
let printers = craft_print::printers().into_iter().map(Printer::from).collect();
let _ = sender.send(printers);
});
receiver
@@ -34,12 +31,17 @@ pub fn submit() -> Submit {
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::Builder::new().name("print-submit".into()).spawn(move || {
let job = craft_print::Job {
printer: Some(settings.printer),
printer: match settings.destination {
Destination::Printer(name) => Some(name),
_ => None,
},
copies: settings.copies.clamp(1, 999),
duplex: settings.duplex.map(|value| match value {
Duplex::LongEdge => craft_print::Duplex::LongEdge,
Duplex::ShortEdge => craft_print::Duplex::ShortEdge,
Duplex::Off => craft_print::Duplex::Off,
collate: settings.collate,
duplex: settings.duplex.and_then(|value| match value {
Duplex::LongEdge => Some(craft_print::Duplex::LongEdge),
Duplex::ShortEdge => Some(craft_print::Duplex::ShortEdge),
Duplex::Off => Some(craft_print::Duplex::Off),
_ => None,
}),
grayscale: settings.grayscale,
scaling: craft_print::Scaling::ShrinkToFit,
+81
View File
@@ -0,0 +1,81 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so the MSI's
//! advertised shortcuts keep matching it.
use std::sync::OnceLock;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdentityError(String);
impl std::fmt::Display for IdentityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for IdentityError {}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
#[test]
fn a_non_nightly_build_never_reaches_the_windows_api() {
assert!(initialize(false, "nightly-id").is_ok());
}
}
+318
View File
@@ -0,0 +1,318 @@
//! GridCraft's nightly profile specification and control-directory boundary, backed by
//! `craft-nightly`. Every stable place a GridCraft build keeps user state or installs is fenced off
//! so the two channels can never share a file.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use craft_nightly::AppProfileSpec;
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
pub const CONTROL_DIR: &str = "Control";
const PROFILE_FOLDERS: [&str; 2] = [CONTROL_DIR, "logs"];
/// Returns GridCraft's `craft-nightly` isolation specification, preserving every stable data,
/// token, Flatpak, and installer boundary.
pub fn app_spec() -> AppProfileSpec {
AppProfileSpec {
app_id: "gridcraft",
display_name: "GridCraft",
stable_dir_names: &["gridcraft", "GridCraft"],
stable_package_id: gridcraft_ui_egui::channel::APP_ID,
nightly_package_id: gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: &[],
portable_markers: &[],
folder_only_entries: &PROFILE_FOLDERS,
extra_forbidden_roots: extra_forbidden_roots(|key| std::env::var_os(key)),
}
}
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir)) { Some(path) } else { None }
}
/// Platform-specific stable install, token, Flatpak, and macOS state paths beyond the standard OS
/// config/data/cache directories already fenced by `craft-nightly`.
fn extra_forbidden_roots(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
#[cfg(target_os = "windows")]
{
// `gridcraft_mcp`'s control-channel token folder and both MSI install folders
// (`install-policy.wxi`).
let mut roots = Vec::new();
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
roots.push(local.join("Programs").join("ArtCraft").join("GridCraft"));
}
if let Some(profile) = non_empty_abs(&env, "USERPROFILE") {
roots.push(profile.join(".gridcraft"));
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("GridCraft"));
}
}
roots
}
#[cfg(all(unix, not(target_os = "macos")))]
{
let mut roots: Vec<PathBuf> = ["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].into_iter().map(PathBuf::from).collect();
// The stable Flatpak keeps its data in its own per-app folder.
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.gridcraft"));
}
roots
}
#[cfg(target_os = "macos")]
{
let mut roots = vec![PathBuf::from("/Applications/GridCraft.app")];
if let Some(home) = non_empty_abs(&env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.gridcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.gridcraft.savedState"));
roots.push(home.join("Applications/GridCraft.app"));
}
roots
}
#[cfg(not(any(unix, target_os = "windows")))]
{
let _ = env;
Vec::new()
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible
/// ancestor is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
/// `gridcraft_mcp` if a control server is ever started. Resolving it never creates anything.
pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
private_subdirectory(root, CONTROL_DIR, "control folder")
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use craft_nightly::{ProfileError, validate_and_prepare_root};
use super::{CONTROL_DIR, PROFILE_FOLDERS, app_spec, control_directory, extra_forbidden_roots};
struct TempDir {
root: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("gridcraft-profile-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
Self { root }
}
fn path(&self) -> &Path {
&self.root
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
#[test]
fn failed_profile_preparation_does_not_start_with_stable() {
let tmp = TempDir::new("file-root");
let root = tmp.path().join("not-a-directory");
std::fs::write(&root, b"an ordinary file").unwrap();
let argv = craft_nightly::launch_arguments(&root, &[]);
let result =
craft_nightly::prepare_launch(craft_nightly::BuildFlavor::NightlyV1, &app_spec(), argv, &craft_nightly::StartupOptions::default());
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file");
}
#[test]
fn app_spec_preserves_gridcraft_identifiers_and_folder_entries() {
let spec = app_spec();
assert_eq!(spec.app_id, "gridcraft");
assert_eq!(spec.display_name, "GridCraft");
assert_eq!(spec.stable_dir_names, &["gridcraft", "GridCraft"]);
assert_eq!(spec.stable_package_id, gridcraft_ui_egui::channel::APP_ID);
assert_eq!(spec.nightly_package_id, gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert!(spec.forbidden_env_vars.is_empty());
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
}
#[test]
fn extra_forbidden_roots_include_platform_install_and_state_paths() {
let tmp = TempDir::new("extra-roots");
let home = tmp.path().join("home");
let local = tmp.path().join("local");
let program_files = tmp.path().join("program-files");
let env: BTreeMap<&str, OsString> = [
("HOME", home.clone().into_os_string()),
("USERPROFILE", home.clone().into_os_string()),
("LOCALAPPDATA", local.clone().into_os_string()),
("ProgramFiles", program_files.clone().into_os_string()),
]
.into_iter()
.collect();
let roots = extra_forbidden_roots(|key| env.get(key).cloned());
#[cfg(target_os = "windows")]
{
assert!(roots.contains(&local.join("Programs").join("ArtCraft").join("GridCraft")));
assert!(roots.contains(&home.join(".gridcraft")));
assert!(roots.contains(&program_files.join("ArtCraft").join("GridCraft")));
}
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(roots.contains(&PathBuf::from("/usr/bin/gridcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/gridcraft")));
assert!(roots.contains(&PathBuf::from("/opt/gridcraft")));
assert!(roots.contains(&home.join(".var/app/ai.storyteller.gridcraft")));
}
#[cfg(target_os = "macos")]
{
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.gridcraft.plist")));
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.gridcraft.savedState")));
assert!(roots.contains(&home.join("Applications/GridCraft.app")));
assert!(roots.contains(&PathBuf::from("/Applications/GridCraft.app")));
}
let _ = (&local, &program_files);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_entries() {
let tmp = TempDir::new("reopen");
let private = tmp.path().join("nightly-profile");
let spec = app_spec();
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(
matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
"{name} must stay a directory"
);
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn extra_forbidden_root_overlap_and_traversal_are_refused() {
let tmp = TempDir::new("forbidden");
let forbidden = tmp.path().join("stable-boundary");
let mut spec = app_spec();
spec.extra_forbidden_roots.push(forbidden.clone());
assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(matches!(validate_and_prepare_root(&forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(!forbidden.exists());
assert!(matches!(validate_and_prepare_root(Path::new("relative/profile"), &spec), Err(ProfileError::RelativeProfileRoot(_))));
assert!(matches!(validate_and_prepare_root(&tmp.path().join("a/../b"), &spec), Err(ProfileError::ParentTraversalInProfileRoot(_))));
}
#[test]
fn the_control_folder_is_a_private_lazy_subfolder() {
let tmp = TempDir::new("control");
let private = validate_and_prepare_root(&tmp.path().join("nightly-profile"), &app_spec()).unwrap();
let control = control_directory(&private).unwrap();
assert!(control.starts_with(&private) && control != private);
assert!(!control.exists(), "resolving it must not create it");
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
}
#[cfg(unix)]
#[test]
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let tmp = TempDir::new("control-symlink");
let outside = tmp.path().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = tmp.path().join("nightly-control");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
assert!(control_directory(&private).is_err());
assert!(matches!(validate_and_prepare_root(&private, &app_spec()), Err(ProfileError::SymlinkEntry(_))));
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
}
+13
View File
@@ -50,3 +50,16 @@ ID and `packaging/linux/ai.storyteller.gridcraft.desktop`.
Edit `gridcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, and `iconutil` for the
`.icns` (macOS only). It packs the `.ico` with `cargo xtask ico`.
## Nightly channel
The nightly (`nightly-v1`) derivatives keep the artwork, geometry and the Mac padding unchanged and
change only the field colour: `#1f9d55` in the stable icon, `#14532d` in
`gridcraft-nightly.svg`. There is no letter, badge or crescent; the app and the Launcher name the
channel in text (`GridCraft Nightly`, the `ai.storyteller.gridcraft.nightly-v1` window id).
`gridcraft-nightly.svg` is the vector master. `packaging/nightly-icons.py` renders every frame from
it at its own size (never an upscale) and packs the nine-frame ICO and the eleven-slot ICNS; it
uses `resvg` when present, else a headless Chrome. Each output's SHA-256, the palette and the
method are recorded in [`nightly-provenance.json`](nightly-provenance.json), and
`python3 packaging/nightly-icons.py --check` verifies the committed files still match it.
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+30
View File
@@ -0,0 +1,30 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<!-- GridCraft Nightly (nightly-v1) icon: the stable artwork with only its background contribution
deepened. Foreground, geometry and alpha are unchanged; no badge, letter or crescent, so the
channel reads from the app and the Launcher in text.
Palette: ink #0b0b0c, paper #efe9dc, stable field #1f9d55
(proposed), nightly field #14532d. -->
<defs>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>
</defs>
<g clip-path="url(#tile)">
<rect width="512" height="512" fill="#14532d"/>
<g transform="rotate(-6 256 268)" stroke="#0b0b0c" stroke-linejoin="round" stroke-linecap="round">
<!-- page with a folded top-right corner -->
<path d="M112 76 H336 L404 144 V440 H112 Z" fill="#efe9dc" stroke-width="14"/>
<path d="M336 76 V144 H404" fill="none" stroke-width="12"/>
<!-- title lines -->
<path d="M146 106 H272 M146 130 H232" stroke-width="12"/>
<!-- header row and row-number column, in the app colour -->
<path d="M112 164 H404 V204 H164 V440 H112 Z" fill="#14532d" stroke="none"/>
<!-- grid -->
<path d="M112 164 H404 M112 204 H404 M112 250 H404 M112 296 H404 M112 342 H404 M112 388 H404
M164 164 V440 M244 164 V440 M324 164 V440" fill="none" stroke-width="8"/>
<!-- the selected cell and its fill handle -->
<rect x="244" y="250" width="80" height="46" fill="none" stroke-width="16"/>
<rect x="312" y="284" width="24" height="24" fill="#0b0b0c" stroke="#efe9dc" stroke-width="5"/>
<!-- double rule under the total -->
<path d="M252 410 H316 M252 424 H316" stroke-width="7"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

+56
View File
@@ -0,0 +1,56 @@
{
"title": "GridCraft nightly deep-background icons",
"author": "@skylartaylor",
"license": "MIT OR Apache-2.0",
"inputs": [
{
"path": "assets/app-icon/gridcraft-nightly.svg",
"sha256": "671748d45b785a840cf6ad062024c008e4704edc8925bed986dac2558438516b",
"purpose": "vector master for every frame"
},
{
"path": "assets/app-icon/gridcraft.svg",
"sha256": "a4c55f2f52893b319862b610c006af83da9f097a4112b5a982b8ba95f43d2850",
"purpose": "stable artwork this is derived from"
}
],
"method": {
"kind": "vector render of the project-owned artwork with only its field colour deepened",
"stable_field": "#1f9d55",
"nightly_field": "#14532d",
"unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding",
"sizes": "each frame rendered at its own size, never upscaled",
"renderer": "chrome",
"generator": "packaging/nightly-icons.py"
},
"outputs": {
"gridcraft-nightly.png": "f06a2507dbd07c307d3b3e46eb2b7d849c29cc51f56114d61091d68d9d59e0d0",
"gridcraft-nightly-1024.png": "914314b91dd214132bc017503d88197ca1537fab0de144a59cc65e03a03be400",
"gridcraft-nightly.ico": "20cdb98a65c157f1db67800d439730b2c5dd564722d615d2b9483dc948f6e751",
"gridcraft-nightly.icns": "e8fb90269660151b8ab1370bbd7194f5bae29888aa44959cf4c48110dcdebe9a"
},
"ico_frame_sizes": [
16,
20,
24,
32,
40,
48,
64,
128,
256
],
"icns_png_slots": {
"icp4": 16,
"icp5": 32,
"ic11": 32,
"icp6": 64,
"ic12": 64,
"ic07": 128,
"ic08": 256,
"ic13": 256,
"ic09": 512,
"ic14": 512,
"ic10": 1024
}
}
-3
View File
@@ -11,7 +11,4 @@ disallowed-methods = [
{ path = "std::time::SystemTime::now", reason = "traps on wasm; read the clock only off wasm" },
]
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+6
View File
@@ -118,3 +118,9 @@ sync_github_name = true
[people.RockerHX]
sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
[people.alosslessdev]
real_name = "Francisco Herrera"
+71 -8
View File
@@ -18,7 +18,7 @@ mod lambda;
mod reference_fns;
mod special;
use array::map_unary;
use array::{binary_scalar_snapped, map_unary};
pub use array::{binary_values, zip2};
pub use format::r1c1_to_a1;
pub use special::{SPECIAL_FUNCTIONS, is_known_function, precedents, resized_sum_range};
@@ -62,6 +62,28 @@ pub struct Lambda {
pub env: Vec<(String, Ev)>,
}
/// What the tail of a LAMBDA body came to.
enum Tail {
Done(Ev),
/// A call to make in place of the current one, its arguments evaluated.
Call(Arc<Lambda>, Vec<(String, Ev)>),
}
/// A tail call can pass a closure that captures the previous one, thousands deep. Releasing the
/// chain is a loop, not a recursion, so it cannot overflow the native stack.
impl Drop for Lambda {
fn drop(&mut self) {
let mut pending = std::mem::take(&mut self.env);
while let Some((_, ev)) = pending.pop() {
if let Ev::L(l) = ev
&& let Ok(mut inner) = Arc::try_unwrap(l)
{
pending.append(&mut inner.env);
}
}
}
}
#[derive(Clone, Debug)]
pub enum Ev {
V(Value),
@@ -84,6 +106,11 @@ fn err(e: CellError) -> Ev {
/// calls in progress, so it still runs.
const MAX_LAMBDA_CALLS: usize = 140;
/// Tail calls one LAMBDA call may chain. They run in a loop on one native frame, so this only keeps
/// an endless tail recursion finite. Excel computes a tail countdown to 5,459 and answers `#NUM!`
/// for 5,460, which is 5,460 invocations in the chain.
const MAX_TAIL_CALLS: usize = 5460;
/// Native stack, in bytes, that one formula's evaluation may use below its first `eval`. Past it,
/// `eval` answers `#NUM!`. It guards the stack and leaves 128 KiB of a 1 MiB thread for the frames
/// above the formula. A cell that another cell's formula computes on demand shares the budget of the
@@ -305,6 +332,27 @@ impl<'h> Evaluator<'h> {
self.deref(ev)
}
/// Evaluates the root of a formula. Excel snaps a near-cancelling add or subtract to exactly 0
/// only here (and in the last addition of a `SUM`), never inside parentheses, unary signs,
/// `IF` branches or an inner step: `=A1-B1` is 0 over two numbers one ulp apart, `=(A1-B1)` is not.
pub fn value_root(&mut self, e: &Expr) -> Value {
match e {
Expr::Binary(op @ (BinOp::Add | BinOp::Sub), a, b) => {
// The root skips `eval`, so it must pass `eval`'s guards itself: a name that refers to
// itself (directly or through cells) is bounded only by them.
if let Err(x) = self.enter() {
return Value::Error(x);
}
let x = self.value(a);
let y = self.value(b);
self.depth -= 1;
let sys = self.host.workbook().date_system;
zip2(&x, &y, |l, r| binary_scalar_snapped(*op, l, r, sys))
}
_ => self.value(e),
}
}
fn resolve_sheet(&self, s: &SheetSel) -> Result<Vec<usize>, CellError> {
let wb = self.host.workbook();
match s {
@@ -391,25 +439,34 @@ impl<'h> Evaluator<'h> {
}
pub fn eval(&mut self, e: &Expr) -> Ev {
if let Err(x) = self.enter() {
return err(x);
}
let r = self.eval_inner(e);
self.depth -= 1;
r
}
/// `eval`'s guards, shared with [`Self::value_root`]: the stack budget and the nesting depth.
/// On `Ok` the depth is one level deeper, and the caller steps it back.
fn enter(&mut self) -> Result<(), CellError> {
let here = stack_position();
if self.depth == 0 {
self.stack_top = self.host.stack_top().unwrap_or(here);
}
if self.stack_top.abs_diff(here) > STACK_BUDGET {
self.host.stack_exhausted();
return err(CellError::Num);
return Err(CellError::Num);
}
if !self.spend(1) {
return err(CellError::Calc);
return Err(CellError::Calc);
}
self.depth += 1;
if self.depth > MAX_DEPTH {
self.depth -= 1;
return err(CellError::Num);
return Err(CellError::Num);
}
let r = self.eval_inner(e);
self.depth -= 1;
r
Ok(())
}
fn eval_inner(&mut self, e: &Expr) -> Ev {
@@ -491,7 +548,13 @@ impl<'h> Evaluator<'h> {
let saved = self.sheet;
// Unqualified references in a name refer to the scope sheet.
self.sheet = scope;
let r = self.eval(&expr);
// A name's body is a formula of its own, so Excel snaps it by the root rule wherever
// the name is used (name probe, observed on Windows Excel 16.0.20430). Only a
// value-producing add or subtract needs it; any other body, a range included, stays as it is.
let r = match &expr {
Expr::Binary(BinOp::Add | BinOp::Sub, ..) => Ev::V(self.value_root(&expr)),
_ => self.eval(&expr),
};
self.sheet = saved;
r
}
+32 -11
View File
@@ -22,17 +22,32 @@ impl Agg {
/// What a folded aggregate carries from one value to the next.
#[derive(Default)]
pub(super) struct Acc {
pub(super) sum: f64,
/// The sum of every number but the last, left to right.
sum: f64,
/// The last number seen: `SUM` snaps only its last addition (see `gridcraft_core::arith::sum_snapped`).
last: Option<f64>,
pub(super) count: u64,
}
impl Acc {
pub(super) fn add(&mut self, n: f64) {
if let Some(prev) = self.last.replace(n) {
self.sum += prev;
}
}
/// Fold a precomputed range sum into an empty accumulator.
pub(super) fn add_range_sum(&mut self, sum: f64, count: u64) {
self.sum = sum;
self.count = self.count.saturating_add(count);
}
/// Takes a value found inside a reference: only numbers count. `Err` is an error value that
/// ends `SUM` and `AVERAGE`; `COUNT` skips errors.
pub(super) fn add_cell(&mut self, kind: Agg, v: &Value) -> Result<(), CellError> {
match v {
Value::Number(n) => {
self.sum += n;
self.add(*n);
self.count = self.count.saturating_add(1);
Ok(())
}
@@ -42,11 +57,12 @@ impl Acc {
}
pub(super) fn finish(&self, kind: Agg) -> Value {
let plain = self.sum + self.last.unwrap_or(0.0);
match kind {
Agg::Sum => Value::number(self.sum),
Agg::Sum => Value::number(self.last.map_or(self.sum, |l| gridcraft_core::arith::snap_add(self.sum, l))),
Agg::Count => Value::number(self.count as f64),
Agg::Average if self.count == 0 => Value::Error(CellError::Div0),
Agg::Average => Value::number(self.sum / self.count as f64),
Agg::Average => Value::number(plain / self.count as f64),
}
}
}
@@ -172,6 +188,17 @@ pub fn binary_values(op: BinOp, x: &Value, y: &Value, sys: gridcraft_core::DateS
zip2(x, y, |a, b| binary_scalar(op, a, b, sys))
}
/// `a + b` or `a - b` with Excel's snap to zero (see [`super::Evaluator::value_root`]).
pub(super) fn binary_scalar_snapped(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSystem) -> Value {
match (a, b) {
(Value::Error(_), _) | (_, Value::Error(_)) => binary_scalar(op, a, b, sys),
_ => match (a.to_number_in(sys), b.to_number_in(sys)) {
(Ok(x), Ok(y)) => Value::number(gridcraft_core::arith::snap_add(x, if op == BinOp::Sub { -y } else { y })),
(Err(e), _) | (_, Err(e)) => Value::Error(e),
},
}
}
/// `x & y` with at least one array operand, giving `#NUM!` once the texts built so far pass `budget`
/// bytes.
fn concat_arrays(x: &Value, y: &Value, sys: gridcraft_core::DateSystem, budget: usize) -> Value {
@@ -216,13 +243,7 @@ fn binary_scalar(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSyste
}
}),
BinOp::Concat => match (a.to_text(), b.to_text()) {
(Ok(x), Ok(y)) => {
if x.len() + y.len() > 32767 * 4 {
Value::Error(CellError::Value)
} else {
Value::text(x + &y)
}
}
(Ok(x), Ok(y)) => Value::text(gridcraft_core::cap_text(x + &y)),
(Err(e), _) | (_, Err(e)) => Value::Error(e),
},
BinOp::Eq => Value::Bool(compare(a, b) == Equal),
+24 -12
View File
@@ -5,6 +5,17 @@ use super::{Area, Arg, Array, CellError, Ev, Evaluator, Expr, FnCtx, Lambda, Pip
use std::sync::Arc;
impl<'h> Evaluator<'h> {
/// `IF` with an array condition: element-wise.
pub(super) fn if_elementwise(&mut self, arr: &Array, args: &[Expr]) -> Ev {
let t = self.arg_val(args, 1).unwrap_or(Value::Bool(true));
let f = if args.len() > 2 { self.arg_val(args, 2).unwrap_or(Value::Bool(false)) } else { Value::Bool(false) };
Ev::V(zip3(arr, &t, &f, |c, t, f| match c.to_bool() {
Ok(true) => t.clone(),
Ok(false) => f.clone(),
Err(e) => Value::Error(e),
}))
}
pub(super) fn call(&mut self, name: &str, args: &[Expr]) -> Ev {
match name {
"IF" => self.if_call(args),
@@ -402,13 +413,13 @@ impl<'h> Evaluator<'h> {
/// Adds one area to `acc`; `Err` is the result the function ends with.
fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> {
if !a.range.is_single() {
// Adding the block's remembered sum to anything but +0.0 would add in another order.
// COUNT never reads the sum, so it may reuse every block.
if (kind == Agg::Count || acc.sum.to_bits() == 0)
&& let Some((sum, count)) = self.host.range_sum(a.sheet, a.range)
// COUNT never reads the sum, so it may reuse every block's remembered count.
// SUM and AVERAGE must walk so SUM can snap only its last addition (the remembered
// block sum does not keep that last add).
if kind == Agg::Count
&& let Some((_sum, count)) = self.host.range_sum(a.sheet, a.range)
{
acc.sum = sum;
acc.count = acc.count.saturating_add(count);
acc.add_range_sum(0.0, count);
return Ok(());
}
// Folded without building an array, but still walked: the part inside the used
@@ -433,20 +444,21 @@ impl<'h> Evaluator<'h> {
self.aggregate_value(kind, value, true, acc)
}
/// Adds one argument's value by calling `SUM` and `COUNT` on it, so coercion and error rules
/// stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`).
/// Adds one argument's value with `SUM`'s numbers and a call to `COUNT`, so coercion and error
/// rules stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`). The numbers
/// are added one by one so `SUM` can snap only its last addition.
fn aggregate_value(&mut self, kind: Agg, value: Value, from_ref: bool, acc: &mut Acc) -> Result<(), Ev> {
if !from_ref && !self.spend_on(&value) {
return Err(err(CellError::Calc));
}
let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), gridcraft_functions::lookup("COUNT")) else {
let Some(count) = gridcraft_functions::lookup("COUNT") else {
return Err(err(CellError::Name));
};
let args = [Arg { value, from_ref, blank_value: false }];
if kind != Agg::Count {
match gridcraft_functions::call(sum, &args, &mut FnCtx { ev: self, criteria: None, lambda: None }) {
Value::Number(n) => acc.sum += n,
other => return Err(Ev::V(other)),
match gridcraft_functions::numbers(&args) {
Ok(ns) => ns.into_iter().for_each(|n| acc.add(n)),
Err(e) => return Err(err(e)),
}
}
if kind != Agg::Sum {
+88 -4
View File
@@ -1,17 +1,26 @@
use super::MAX_LAMBDA_CALLS;
use super::array::{broadcast_len, single};
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, Value, err};
use super::special::is_special;
use super::{Array, BinOp, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
use std::sync::Arc;
impl<'h> Evaluator<'h> {
pub fn apply_lambda(&mut self, l: &Lambda, args: &[Expr]) -> Ev {
match self.bind_args(l, args) {
Ok(bound) => self.call_lambda_values(l, bound),
Err(e) => e,
}
}
/// The arguments of a call to `l`, evaluated in the current scope.
fn bind_args(&mut self, l: &Lambda, args: &[Expr]) -> Result<Vec<(String, Ev)>, Ev> {
// Too many or too few argument positions is #VALUE!. An explicitly empty position, as in
// `(1,)`, is `Expr::Missing` and still counts as a position (it binds as omitted). `f()`
// parses to no arguments, which for a one-parameter lambda can also be read as one empty
// position, so that call still binds the parameter as omitted.
let positions_ok = args.len() == l.params.len() || (args.is_empty() && l.params.len() == 1);
if !positions_ok {
return err(CellError::Value);
return Err(err(CellError::Value));
}
let mut bound = Vec::with_capacity(l.params.len());
for (i, p) in l.params.iter().enumerate() {
@@ -21,7 +30,56 @@ impl<'h> Evaluator<'h> {
};
bound.push((p.clone(), v));
}
self.call_lambda_values(l, bound)
Ok(bound)
}
/// Follows `e` through the positions whose value is the value of a LAMBDA call (`IF` branches,
/// parentheses), and returns the call with its arguments evaluated instead of making it, so
/// that `call_lambda_values` can loop. Anything else is evaluated here.
fn tail_step(&mut self, e: &Expr) -> Tail {
match e {
Expr::Paren(x) => self.tail_step(x),
Expr::Call(name, args) if name == "IF" && (2..=3).contains(&args.len()) => {
let c = self.arg_val(args, 0).unwrap_or_default();
if let Value::Array(arr) = &c {
return Tail::Done(self.if_elementwise(arr, args));
}
match c.to_bool() {
Ok(true) => self.tail_step_branch(args.get(1)),
Ok(false) => match args.get(2) {
Some(_) => self.tail_step_branch(args.get(2)),
None => Tail::Done(Ev::V(Value::Bool(false))),
},
Err(x) => Tail::Done(err(x)),
}
}
Expr::Call(name, args) if gridcraft_functions::lookup(name).is_none() && !is_special(name) => match self.name(name) {
Ev::L(l) => self.tail_call(l, args),
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
_ => Tail::Done(err(CellError::Name)),
},
Expr::Invoke(callee, args) => match self.eval(callee) {
Ev::L(l) => self.tail_call(l, args),
Ev::V(Value::Error(x)) => Tail::Done(err(x)),
_ => Tail::Done(err(CellError::Value)),
},
_ => Tail::Done(self.eval(e)),
}
}
/// An `IF` branch; an omitted one (`IF(c,,1)`) is 0.
fn tail_step_branch(&mut self, branch: Option<&Expr>) -> Tail {
match branch {
Some(Expr::Missing) | None => Tail::Done(Ev::V(Value::Number(0.0))),
Some(b) => self.tail_step(b),
}
}
fn tail_call(&mut self, l: Arc<Lambda>, args: &[Expr]) -> Tail {
match self.bind_args(&l, args) {
Ok(bound) => Tail::Call(l, bound),
Err(e) => Tail::Done(e),
}
}
pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev {
@@ -38,7 +96,33 @@ impl<'h> Evaluator<'h> {
self.calls += 1;
let saved = std::mem::replace(&mut self.env, l.env.clone());
self.env.extend(bound);
let r = self.eval(&l.body);
// A LAMBDA body is a formula of its own, so Excel snaps it by the root rule in every context
// (named, inline, LET-bound, MAP, REDUCE, SCAN, MAKEARRAY, BYROW, BYCOL; LAMBDA probe, observed
// on Windows Excel 16.0.20430). A LET, IF, parenthesis or unary sign at the root of the body does not.
// A call in tail position replaces this one instead of nesting under it, so a tail recursion
// uses no more native stack at 5,000 deep than at 5. Each link still spends fuel.
let snap_root = |body: &Expr| matches!(body, Expr::Binary(BinOp::Add | BinOp::Sub, ..));
let mut tails = 0;
let mut step = if snap_root(&l.body) { Tail::Done(Ev::V(self.value_root(&l.body))) } else { self.tail_step(&l.body) };
let r = loop {
match step {
Tail::Done(v) => break v,
Tail::Call(next, bound) => {
tails += 1;
if tails >= MAX_TAIL_CALLS {
break err(CellError::Num);
}
self.fuel = match self.fuel.checked_sub(1) {
Some(f) => f,
None => break err(CellError::Calc),
};
self.env.clear();
self.env.extend(next.env.iter().cloned());
self.env.extend(bound);
step = if snap_root(&next.body) { Tail::Done(Ev::V(self.value_root(&next.body))) } else { self.tail_step(&next.body) };
}
}
};
self.env = saved;
self.calls -= 1;
r
+1 -1
View File
@@ -195,7 +195,7 @@ impl Precedents<'_> {
}
}
fn is_special(n: &str) -> bool {
pub(super) fn is_special(n: &str) -> bool {
matches!(
n,
"IF" | "IFS"
+1 -1
View File
@@ -12,7 +12,7 @@ mod trimrange;
pub use eval::{Area, SPECIAL_FUNCTIONS, is_known_function};
pub use precision::DisplayedPrecision;
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial};
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, evaluate_expr, now_serial};
#[cfg(test)]
mod tests;
+14 -3
View File
@@ -718,7 +718,7 @@ impl Calc {
} else {
Vec::new()
};
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing, array.data.len());
if !blocked {
for (o, r) in outranked {
for c in r.iter() {
@@ -785,6 +785,7 @@ fn spill_is_blocked(
range: RangeRef,
end: CellRef,
standing: &Standing,
array_len: usize,
) -> bool {
let outranked = |cell: CellRef| {
sheet
@@ -796,7 +797,7 @@ fn spill_is_blocked(
|| end.col >= gridcraft_core::MAX_COLS
|| range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell))))
|| sheet.merges.iter().any(|merge| merge.intersects(&range))
|| sheet.tables.iter().any(|table| table.range.contains(anchor.1))
|| (array_len > 1 && sheet.tables.iter().any(|table| table.range.contains(anchor.1)))
}
fn fill_spill(sheet: &mut gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, array: &Array) {
@@ -824,11 +825,21 @@ pub fn evaluate(wb: &Workbook, sheet: usize, at: CellRef, formula: &str) -> Valu
}
pub fn evaluate_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> Value {
evaluate_expr_at(wb, sheet, at, expr, true)
}
/// Like [`evaluate_expr`] for a sub-expression of a larger formula (Evaluate Formula's steps): Excel's
/// snap to zero applies at a formula's root only, so an inner `A1-B1` keeps its IEEE residue.
pub fn evaluate_inner_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> Value {
evaluate_expr_at(wb, sheet, at, expr, false)
}
fn evaluate_expr_at(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr, root: bool) -> Value {
let exprs = HashMap::default();
let mut rng = 0x1234_5678_9ABC_DEF0u64;
let mut host = PassHost::new(wb, &exprs, &mut rng, now_serial());
let mut ev = Evaluator::new(&mut host, sheet, at);
ev.value(expr)
if root { ev.value_root(expr) } else { ev.value(expr) }
}
/// What [`evaluate_bounded`] found: the formula's reference (not read), its value, or that it ran
+5 -4
View File
@@ -162,7 +162,8 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range:
})
}
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
/// Whether an array result at `k` can't spill: it is in a table (a one-value result is shown
/// there, as in Excel), or its area runs off the sheet,
/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on
/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so
/// may spill elsewhere now). A spill it outranks gives way to it when written back.
@@ -188,7 +189,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool {
end.row >= gridcraft_core::MAX_ROWS
|| end.col >= gridcraft_core::MAX_COLS
|| sh.merges.iter().any(|m| m.intersects(&range))
|| sh.tables.iter().any(|t| t.range.contains(anchor))
|| (a.data.len() > 1 && sh.tables.iter().any(|t| t.range.contains(anchor)))
|| sh.cells.iter_range(range).any(|(c, cell)| c != anchor && (!cell.value.is_empty() || cell.formula.is_some()))
|| sh.spill.range(range.start..=range.end).any(|(c, _)| range.contains(*c) && spilled_over(*c))
}
@@ -200,7 +201,7 @@ pub(super) fn spills_as_before(sheet: &gridcraft_model::Sheet, anchor: CellRef,
CellRef::new(anchor.row.saturating_add((arr.rows as u32).saturating_sub(1)), anchor.col.saturating_add((arr.cols as u32).saturating_sub(1)));
RangeRef::new(anchor, end) == range
&& !sheet.merges.iter().any(|m| m.intersects(&range))
&& !sheet.tables.iter().any(|t| t.range.contains(anchor))
&& (arr.data.len() <= 1 || !sheet.tables.iter().any(|t| t.range.contains(anchor)))
&& range
.iter()
.enumerate()
@@ -331,7 +332,7 @@ impl PassHost<'_> {
let outer_out_of_stack = std::mem::replace(&mut self.out_of_stack, false);
let v = {
let mut ev = Evaluator::new(self, k.0, k.1);
ev.value(&expr)
ev.value_root(&expr)
};
let out_of_stack = std::mem::replace(&mut self.out_of_stack, outer_out_of_stack);
if out_of_stack && self.depth > 1 && self.suspend.is_none() {
+644 -7
View File
@@ -820,6 +820,42 @@ fn arrays_do_not_spill_in_tables() {
assert_eq!(t.num("E4"), 4.0);
}
#[test]
fn one_value_array_in_a_table_is_not_a_spill() {
// Excel shows a one-value dynamic-array result in a table column; two or more is #SPILL! (#2335).
let table = |range: &str| gridcraft_model::Table {
id: 1,
name: "Table1".into(),
range: gridcraft_core::RangeRef::parse(range).unwrap(),
header_row: true,
totals_row: false,
columns: vec![],
style: String::new(),
banded_rows: false,
banded_cols: false,
first_col: false,
last_col: false,
filter_button: false,
filter: vec![],
table_type: None,
connection_id: None,
};
let mut t = T::new();
t.wb.sheet_mut(0).unwrap().tables.push(table("B3:C6"));
t.set("A1", "7");
t.set("A2", "8");
t.set("C4", "=FILTER(A1:A2,A1:A2>7)");
t.set("C5", "=FILTER(A1:A2,A1:A2>0)");
t.set("H4", "=FILTER(A1:A2,A1:A2>7)");
t.set("D4", "=ROWS(C4#)");
assert_eq!((t.num("C4"), t.num("H4"), t.num("D4")), (8.0, 8.0, 1.0));
assert_eq!(t.get("C5"), Value::Error(CellError::Spill));
// Recalculating again keeps the one-value result.
t.calc.recalc_all(&mut t.wb);
assert_eq!(t.num("C4"), 8.0);
assert_eq!(t.num("D4"), 1.0);
}
#[test]
fn ifs_and_lazy() {
let mut t = T::new();
@@ -1181,17 +1217,67 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() {
comment: String::new(),
hidden: false,
});
// F(F,n) has n + 1 calls in progress at its deepest; W adds one more call per step.
// W's call to `f` is a tail call, so a wrapped call level costs one call in progress, not two. A tail call reuses its frame, so the tail chain is bounded by `MAX_TAIL_CALLS`, as in Excel
// (5,459 ok, 5,460 #NUM!). F(F,n) otherwise has n + 1 calls in progress at its deepest; W adds
// one more call per step.
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
let wrapped = |n: u32| format!("=LET(W,LAMBDA(f,k,f(f,k)),F,LAMBDA(me,n,IF(n<=0,0,1+W(me,n-1))),F(F,{n}))");
[tail(139), tail(140), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
[tail(5459), tail(5460), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
})
.expect("spawn")
.join()
.expect("recursion must not overflow the stack")
};
let small = run(1 << 20);
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]);
assert_eq!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Number(70.0), Value::Number(131.0)]);
assert_eq!(run(64 << 20), small);
}
#[test]
fn a_tail_recursive_lambda_reaches_excels_depth_on_a_small_stack() {
// Excel (measured): a tail countdown is 0 at 5,000 and 5,459 and #NUM! at 5,460 and 10,000.
let run = |stack: usize| {
std::thread::Builder::new()
.stack_size(stack)
.spawn(|| {
let mut wb = Workbook::new();
wb.names.push(gridcraft_model::DefinedName {
name: "TAILN".into(),
scope: None,
formula: "LAMBDA(n,IF(n=0,0,TAILN(n-1)))".into(),
comment: String::new(),
hidden: false,
});
let tail = |n: u32| format!("=LET(F,LAMBDA(me,n,IF(n=0,0,me(me,n-1))),F(F,{n}))");
// The same chain through parentheses and an applied lambda, and one that returns the base case's value.
let paren = "=LET(F,LAMBDA(me,n,IF(n=0,7,(me(me,n-1)))),F(F,5000))".to_string();
let invoke = "=LET(F,LAMBDA(me,n,IF(n=0,7,LAMBDA(a,b,me(me,a))(n-1,0))),F(F,2000))".to_string();
let endless = "=LET(f,LAMBDA(g,x,g(g,x)),f(f,1))".to_string();
// Each call passes a closure that captures the last, 5,000 deep: releasing them must not recurse.
let closures = "=LET(F,LAMBDA(me,n,acc,IF(n=0,0,me(me,n-1,LAMBDA(x,acc)))),F(F,5000,0))".to_string();
[tail(5000), tail(5459), tail(5460), tail(10000), paren, invoke, endless, "=TAILN(5000)".to_string(), closures]
.map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
})
.expect("spawn")
.join()
.expect("tail recursion must not overflow the stack")
};
let num = Value::Error(CellError::Num);
let small = run(1 << 20);
assert_eq!(
small,
[
Value::Number(0.0),
Value::Number(0.0),
num.clone(),
num.clone(),
Value::Number(7.0),
Value::Number(7.0),
num,
Value::Number(0.0),
Value::Number(0.0)
]
);
assert_eq!(run(64 << 20), small);
}
@@ -1632,6 +1718,478 @@ fn sumif_resized_sum_range_on_another_sheet_and_through_a_name() {
assert_eq!(t.num("C2"), 5.0);
}
// ---- Excel's snap to zero (observed on Windows Excel 16.0.20430; suite rows cancel-ulps, cancel-band, decimal-sum, excel-probe) ----
impl T {
/// Stores an exact double, bypassing input parsing.
fn put(&mut self, at: &str, x: f64) {
self.wb.sheet_mut(0).unwrap().cells.set(c(at), Cell::value(Value::Number(x)));
self.calc.cells_changed(&mut self.wb, &[(0, c(at))]);
}
}
const ULP1: f64 = f64::EPSILON; // the spacing of doubles just above 1.0
#[test]
fn a_bare_root_add_or_sub_snaps_a_near_cancellation_to_zero() {
let mut t = T::new();
t.put("A1", 1.0);
t.put("B1", 1.0 + ULP1); // one ulp apart: Excel shows 0, not -2.22e-16
t.set("C1", "=A1-B1");
t.set("C2", "=B1-A1");
t.set("C3", "=A1+-B1");
t.set("C4", "=0+A1-B1"); // the end of =0+A-B snaps too
t.set("C5", "=SUM(A1,-B1)*1"); // the last addition of a SUM snaps even when SUM isn't the root
t.put("D1", -(1.0 + ULP1));
t.set("C6", "=SUM(A1,D1)");
t.set("C7", "=A1+D1");
for at in ["C1", "C2", "C3", "C4", "C5", "C6", "C7"] {
assert_eq!(t.get(at), Value::Number(0.0), "{at}");
}
// The classic: 0.1+0.2-0.3 is 0 in Excel (5.55e-17 in IEEE).
t.put("E1", 0.1);
t.put("E2", 0.2);
t.put("E3", 0.3);
t.set("E4", "=E1+E2-E3");
assert_eq!(t.get("E4"), Value::Number(0.0));
}
#[test]
fn sum_snaps_its_last_addition_when_it_folds_a_range_in_place() {
// SUM, COUNT and AVERAGE fold ranges over the stored cells instead of calling SUM; the fold must
// keep SUM's rule: only the last number added snaps, and a blank cell adds no number.
let mut t = T::new();
t.put("A1", 1.0);
t.put("A2", -(1.0 + ULP1));
t.set("C1", "=SUM(A1:A2)");
t.set("C2", "=SUM(A1:A2,Z9)");
t.set("C3", "=SUM(A1:A2,0)"); // the last addition is residue + 0: no snap
t.set("C4", "=AVERAGE(A1:A2)"); // AVERAGE does not snap
assert_eq!(t.get("C1"), Value::Number(0.0));
assert_eq!(t.get("C2"), Value::Number(0.0));
assert_eq!(t.get("C3"), Value::Number(-ULP1));
assert_eq!(t.get("C4"), Value::Number(-ULP1 / 2.0));
}
#[test]
fn the_snap_threshold_is_two_to_the_e_minus_49_of_the_left_operand() {
let mut t = T::new();
t.put("A1", 1.0);
// 7 ulps below the threshold of 8 ulps (2^-49): snaps. Exactly 8: does not.
t.put("B1", 1.0 + 7.0 * ULP1);
t.put("B2", 1.0 + 8.0 * ULP1);
t.set("C1", "=A1-B1");
t.set("C2", "=A1-B2");
assert_eq!(t.get("C1"), Value::Number(0.0));
assert_eq!(t.get("C2"), Value::Number(-8.0 * ULP1));
// The binade is the LEFT operand's (observed on Windows Excel 16.0.20430, excel-probe-4.00044 to 00046).
t.put("A3", 0.4999999999999998);
t.put("B3", 0.5000000000000002);
t.set("C3", "=A3-B3");
t.set("C4", "=B3-A3");
assert_eq!(t.get("C3"), Value::Number(-4.440892098500626e-16));
assert_eq!(t.get("C4"), Value::Number(0.0));
}
#[test]
fn the_snap_does_not_apply_inside_parentheses_unary_if_or_inner_steps() {
let mut t = T::new();
t.put("A1", 1.0);
t.put("B1", 1.0 + ULP1);
let residue = 1.0 - (1.0 + ULP1);
for (at, f) in [
("C1", "=(A1-B1)"),
("C2", "=+(A1-B1)"),
("C3", "=-(B1-A1)"),
("C4", "=IF(TRUE,A1-B1)"),
("C5", "=A1-B1+0"), // the root is the +0; the inner subtraction is not a root
("C6", "=SUM(A1,-B1,0)"), // the last addition is residue+0
] {
t.set(at, f);
assert_eq!(t.get(at), Value::Number(residue), "{f}");
}
// Observed on Windows Excel 16.0.20430: =SUM(A-B) does not snap (the subtraction is an inner step, the SUM's
// last addition is residue + 0), and neither does a root that adds a zero.
t.set("C7", "=SUM(A1-B1)");
t.set("C8", "=A1-B1-0");
assert_eq!(t.get("C7"), Value::Number(residue));
assert_eq!(t.get("C8"), Value::Number(residue));
// Only the LAST addition of a SUM snaps: 3+1e16-1e16 is 4, not 0.
t.put("D1", 3.0);
t.put("D2", 1e16);
t.put("D3", -1e16);
t.put("D4", 0.0);
t.set("E1", "=SUM(D1:D4)");
assert_eq!(t.get("E1"), Value::Number(4.0));
}
#[test]
fn same_sign_and_exact_arithmetic_never_snap() {
let mut t = T::new();
t.put("A1", 1e-20);
t.put("B1", 2e-20);
t.set("C1", "=A1+B1"); // a tiny sum of small numbers is not a cancellation
t.set("C2", "=A1-B1");
t.put("A2", 3.0);
t.put("B2", 2.0);
t.set("C3", "=A2-B2");
assert_eq!(t.num("C1"), 1e-20 + 2e-20);
assert_eq!(t.num("C2"), 1e-20 - 2e-20);
assert_eq!(t.num("C3"), 1.0);
}
#[test]
fn the_snap_threshold_follows_the_left_operand_across_a_binade_boundary() {
// Observed on Windows Excel 16.0.20430, snap probe rows 226, 231 and 236 (=A-B, A just below 1.0): the
// threshold is 2^-50 (A's binade), not 2^-49 (B's), so 7.8e-16 snaps and 9.99e-16 does not.
let mut t = T::new();
t.put("A1", 0.9999999999999999);
t.put("B1", 1.0000000000000004);
t.put("B2", 1.0000000000000007);
t.put("B3", 1.0000000000000009);
t.set("D1", "=A1-B1");
t.set("D2", "=A1-B2");
t.set("D3", "=A1-B3");
assert_eq!(t.get("D1"), Value::Number(0.0));
assert_eq!(t.get("D2"), Value::Number(0.0));
assert_eq!(t.get("D3"), Value::Number(-9.992007221626409e-16));
}
#[test]
fn the_snap_leaves_error_and_text_operands_alone() {
let mut t = T::new();
t.put("B1", 1.0 + ULP1);
t.set("A1", "=1/0");
t.set("C1", "=A1-B1");
assert_eq!(t.get("C1"), Value::Error(CellError::Div0));
t.set("A2", "abc");
t.set("C2", "=A2-B1");
assert_eq!(t.get("C2"), Value::Error(CellError::Value));
t.set("A3", "1"); // numeric text still converts, then the subtraction snaps like any other
t.put("B3", 1.0);
t.set("C3", "=A3-B3");
assert_eq!(t.get("C3"), Value::Number(0.0));
}
// ---- the snap in a defined name's body (observed on Windows Excel 16.0.20430, name probe: 8 bodies x 12 positions) ----
impl T {
fn name(&mut self, name: &str, body: &str) {
self.wb.names.push(gridcraft_model::DefinedName {
name: name.into(),
scope: None,
formula: body.into(),
comment: String::new(),
hidden: false,
});
}
}
#[test]
fn a_defined_name_is_a_formula_of_its_own_so_its_body_snaps_wherever_it_is_used() {
let mut t = T::new();
t.put("A1", 1.0);
t.put("B1", 1.0 + ULP1);
// (body, does Excel snap it?) Only the shape of the BODY matters, not where the name is used.
let bodies = [
("N_sub", "Sheet1!$A$1-Sheet1!$B$1", true),
("N_par", "(Sheet1!$A$1-Sheet1!$B$1)", false),
("N_plus0", "Sheet1!$A$1-Sheet1!$B$1+0", false),
("N_sum", "SUM(Sheet1!$A$1,-Sheet1!$B$1)", true),
("N_neg", "-(Sheet1!$B$1-Sheet1!$A$1)", false),
("N_ref", "N_sub", true), // a name that is a name inherits it
("N_if", "IF(TRUE,Sheet1!$A$1-Sheet1!$B$1)", false),
("N_sumsub", "SUM(Sheet1!$A$1-Sheet1!$B$1)", false),
];
for (name, body, _) in bodies {
t.name(name, body);
}
// All 12 positions of the Excel probe.
let uses = ["{n}", "{n}*1", "{n}+0", "0+{n}", "({n})", "-{n}", "+{n}", "SUM({n})", "IF(TRUE,{n})", "ABS({n})", "1*{n}", "{n}-0"];
let mut row = 2;
for (name, body, snaps) in bodies {
for u in uses {
let at = format!("D{row}");
t.set(&at, &format!("={}", u.replace("{n}", name)));
// Every body is -1 ulp (A1-B1) or exactly 0; a minus sign or ABS flips the residue.
let flips = u.starts_with('-') || u.starts_with("ABS");
let want = if snaps {
0.0
} else if flips {
ULP1
} else {
-ULP1
};
assert_eq!(t.get(&at), Value::Number(want), "{u} over {name} = {body}");
row += 1;
}
}
}
#[test]
fn excels_own_gap_shapes_from_lookup_shapes_xlsx() {
// excel-evidence/request-3/files/lookup-shapes.xlsx, Sheet1!H15:H26: the gaps of 1, 4 and 7 ulps
// snap to 0 as =Gap, =Gap*1 and =Gap+0; the gap of 8 ulps keeps its residue.
let mut t = T::new();
for (cell, v) in [("A1", 1.0000000000000002), ("A2", 1.0000000000000009), ("A3", 1.0000000000000016), ("A4", 1.0000000000000018)] {
t.put(cell, v);
}
for (cell, v) in [("B1", 1.0), ("B2", 1.0), ("B3", 1.0), ("B4", 1.0)] {
t.put(cell, v);
}
for (name, row) in [("Gap_1", 1), ("Gap_4", 2), ("Gap_7", 3), ("Gap_8", 4)] {
t.name(name, &format!("Sheet1!$A${row}-Sheet1!$B${row}"));
}
let mut r = 10;
for (name, residue) in [("Gap_1", 0.0), ("Gap_4", 0.0), ("Gap_7", 0.0), ("Gap_8", 1.7763568394002505e-15)] {
for f in ["{n}", "{n}*1", "{n}+0"] {
let at = format!("F{r}");
t.set(&at, &format!("={}", f.replace("{n}", name)));
assert_eq!(t.get(&at), Value::Number(residue), "{f} over {name}");
r += 1;
}
}
}
#[test]
fn a_name_that_refers_to_a_range_still_refers_to_it() {
// Only a reference answers these: ISREF, ROW and OFFSET over a name. Wrapping every name
// body in value_root would turn the range into an array and fail all three.
let mut t = T::new();
t.put("A1", 1.0);
t.put("A2", 2.0);
t.put("B1", 3.0);
t.put("B2", 4.0);
t.name("Block", "Sheet1!$A$1:$B$2");
t.set("D1", "=ISREF(Block)");
t.set("D2", "=MIN(ROW(Block))");
t.set("D3", "=SUM(OFFSET(Block,0,1))");
assert_eq!(t.get("D1"), Value::Bool(true));
assert_eq!(t.num("D2"), 1.0);
assert_eq!(t.num("D3"), 7.0);
}
#[test]
fn a_name_whose_body_is_an_array_difference_snaps_element_wise() {
// Observed on Windows Excel 16.0.20430 (review probe): INDEX(Arr,1)*1 and INDEX(Arr,2)*1 are 0 for Arr = A1:A2-B1:B2.
let mut t = T::new();
for (a, b) in [("A1", "B1"), ("A2", "B2")] {
t.put(a, 1.0);
t.put(b, 1.0 + ULP1);
}
t.name("Arr", "Sheet1!$A$1:$A$2-Sheet1!$B$1:$B$2");
t.set("D1", "=INDEX(Arr,1)*1");
t.set("D2", "=INDEX(Arr,2)*1");
t.set("D3", "=SUM(Arr)");
assert_eq!((t.get("D1"), t.get("D2")), (Value::Number(0.0), Value::Number(0.0)));
assert_eq!(t.get("D3"), Value::Number(0.0));
}
#[test]
fn a_sheet_scoped_name_snaps_on_its_own_sheet() {
// Observed on Windows Excel 16.0.20430 (review probe): a sheet-scoped Loc = S2!$A$1-S2!$B$1 gives 0 as =S2!Loc*1.
let mut t = T::new();
t.wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("S2")));
t.wb.sheet_mut(1).unwrap().cells.set(c("A1"), Cell::value(Value::Number(1.0)));
t.wb.sheet_mut(1).unwrap().cells.set(c("B1"), Cell::value(Value::Number(1.0 + ULP1)));
t.wb.names.push(gridcraft_model::DefinedName {
name: "Loc".into(),
scope: Some(1),
formula: "S2!$A$1-S2!$B$1".into(),
comment: String::new(),
hidden: false,
});
t.set("D1", "=S2!Loc*1");
t.set("D2", "=S2!Loc");
assert_eq!((t.get("D1"), t.get("D2")), (Value::Number(0.0), Value::Number(0.0)));
}
#[test]
fn recursive_names_stay_bounded_and_cost_the_same_depth_as_before_the_snap() {
let mut t = T::new();
// A name that refers to itself ends in the depth limit's #NUM!, not a stack overflow.
t.name("Rec", "Rec-1");
t.set("A1", "=Rec");
assert_eq!(t.get("A1"), Value::Error(CellError::Num));
// A long chain of names, each one `-0` over the last, runs out of depth at the same place as it did
// before names were snapped (value_root must charge its own level, or each link would be cheaper
// and a chain through cells could overflow the stack).
t.name("Nm_0", "1");
for i in 1..=250 {
t.name(&format!("Nm_{i}"), &format!("Nm_{}-0", i - 1));
}
t.set("A2", "=Nm_250");
assert_eq!(t.get("A2"), Value::Error(CellError::Num));
t.set("A3", "=Nm_20");
assert_eq!(t.get("A3"), Value::Number(1.0));
}
// ---- the snap in a LAMBDA body (observed on Windows Excel 16.0.20430, LAMBDA probe: 126 formulas) ----
// A LAMBDA body is a formula of its own, like a defined name's: Excel snaps it by the root rule in every
// context (named, inline, LET-bound, and under MAP, REDUCE, SCAN, MAKEARRAY, BYROW and BYCOL).
fn lambda_t() -> T {
let mut t = T::new();
t.put("A1", 1.0);
t.put("B1", 1.0 + ULP1);
t.put("A2", 1.0 + ULP1);
t.put("B2", 1.0 + ULP1);
t
}
#[test]
fn a_lambda_body_snaps_by_its_own_root_wherever_the_lambda_is_called() {
let mut t = lambda_t();
// (name, body, does Excel snap it?)
let lambdas = [
("L_sub", "LAMBDA(x,y,x-y)", true),
("L_par", "LAMBDA(x,y,(x-y))", false),
("L_plus0", "LAMBDA(x,y,x-y+0)", false),
("L_sum", "LAMBDA(x,y,SUM(x,-y))", true),
("L_neg", "LAMBDA(x,y,-(y-x))", false),
("L_if", "LAMBDA(x,y,IF(TRUE,x-y))", false),
("L_sumsub", "LAMBDA(x,y,SUM(x-y))", false),
("L_let", "LAMBDA(x,y,LET(d,x-y,d))", false), // a LET inside the body does not snap
("L_letroot", "LAMBDA(x,y,LET(a,x,a-y))", false),
("L_ref", "LAMBDA(x,y,L_sub(x,y))", true), // a lambda that calls one inherits it
];
for (name, body, _) in lambdas {
t.name(name, body);
}
let uses = ["{c}", "{c}*1", "{c}+0", "0+{c}", "({c})", "-{c}", "SUM({c})", "IF(TRUE,{c})", "ABS({c})"];
let mut row = 5;
for (name, body, snaps) in lambdas {
for u in uses {
let at = format!("D{row}");
t.set(&at, &format!("={}", u.replace("{c}", &format!("{name}(Sheet1!$A$1,Sheet1!$B$1)"))));
let flips = u.starts_with('-') || u.starts_with("ABS");
let want = if snaps {
0.0
} else if flips {
ULP1
} else {
-ULP1
};
assert_eq!(t.get(&at), Value::Number(want), "{u} over {name} = {body}");
row += 1;
}
}
}
#[test]
fn inline_and_let_bound_lambdas_snap_the_same_way() {
let mut t = lambda_t();
for (i, (f, snaps)) in [
("LAMBDA(x,y,x-y)(Sheet1!$A$1,Sheet1!$B$1)", true),
("LAMBDA(x,y,x-y)(Sheet1!$A$1,Sheet1!$B$1)*1", true),
("LAMBDA(x,y,(x-y))(Sheet1!$A$1,Sheet1!$B$1)", false),
("LAMBDA(x,y,x-y+0)(Sheet1!$A$1,Sheet1!$B$1)", false),
("LAMBDA(x,y,SUM(x,-y))(Sheet1!$A$1,Sheet1!$B$1)", true),
("LET(f,LAMBDA(x,y,x-y),f(Sheet1!$A$1,Sheet1!$B$1))", true),
("LET(f,LAMBDA(x,y,x-y),f(Sheet1!$A$1,Sheet1!$B$1))*1", true),
("LET(f,LAMBDA(x,y,(x-y)),f(Sheet1!$A$1,Sheet1!$B$1))", false),
]
.into_iter()
.enumerate()
{
let at = format!("D{}", i + 5);
t.set(&at, &format!("={f}"));
assert_eq!(t.get(&at), Value::Number(if snaps { 0.0 } else { -ULP1 }), "{f}");
}
}
#[test]
fn higher_order_functions_snap_their_lambda_body() {
let mut t = lambda_t();
// The cell is INDEX(<result>,1,1), bare and times 1. A is (1, 1+ulp), B is (1+ulp, 1+ulp).
let cases = [
("MAP(Sheet1!$A$1:$A$2,Sheet1!$B$1:$B$2,LAMBDA(x,y,{b}))", "x-y"),
("REDUCE(Sheet1!$A$1,Sheet1!$B$1,LAMBDA(x,y,{b}))", "x-y"),
("SCAN(Sheet1!$A$1,Sheet1!$B$1:$B$2,LAMBDA(x,y,{b}))", "x-y"),
("MAKEARRAY(1,1,LAMBDA(x,y,{b}))", "Sheet1!$A$1-Sheet1!$B$1"),
("BYROW(Sheet1!$A$1:$B$2,LAMBDA(r,{b}))", "INDEX(r,1,1)-INDEX(r,1,2)"),
("BYCOL(Sheet1!$A$1:$B$2,LAMBDA(r,{b}))", "INDEX(r,1,1)-INDEX(r,2,1)"),
];
let mut row = 5;
for (f, bare) in cases {
for (b, snaps) in [(bare.to_string(), true), (format!("({bare})"), false)] {
for u in ["INDEX({c},1,1)", "INDEX({c},1,1)*1"] {
let at = format!("D{row}");
let formula = u.replace("{c}", &f.replace("{b}", &b));
t.set(&at, &format!("={formula}"));
assert_eq!(t.get(&at), Value::Number(if snaps { 0.0 } else { -ULP1 }), "{formula}");
row += 1;
}
}
}
}
#[test]
fn a_lambda_body_that_returns_a_reference_still_returns_one() {
// Observed on Windows Excel 16.0.20430 (review probe): a body that returns a reference is still a reference, so only an
// add or subtract root takes the snapping path. ISREF and OFFSET need the reference; wrapping every
// body in value_root would turn it into a value.
let mut t = lambda_t();
t.set("D5", "=ISREF(LAMBDA(x,x)(Sheet1!$A$1))");
t.set("D6", "=ISREF(LAMBDA(x,IF(TRUE,x))(Sheet1!$A$1))");
t.set("D7", "=ROW(LAMBDA(x,OFFSET(x,1,0))(Sheet1!$A$1))");
assert_eq!(t.get("D5"), Value::Bool(true));
assert_eq!(t.get("D6"), Value::Bool(true));
assert_eq!(t.num("D7"), 2.0);
}
#[test]
fn nested_curried_and_closed_over_lambda_bodies_snap_by_the_root_of_the_inner_body() {
// Observed on Windows Excel 16.0.20430 (review probe): each of these is exactly 0.
let mut t = lambda_t();
for (i, f) in [
"LAMBDA(x,LAMBDA(y,x-y))(Sheet1!$A$1)(Sheet1!$B$1)", // curried
"LAMBDA(x,y,LAMBDA(p,q,p-q)(x,y))(Sheet1!$A$1,Sheet1!$B$1)", // a body that calls an inner lambda
"LAMBDA(x,y,0+x-y)(Sheet1!$A$1,Sheet1!$B$1)", // the end of 0+x-y snaps like =0+A-B
"LET(a,Sheet1!$A$1,LAMBDA(y,a-y)(Sheet1!$B$1))", // a closure over a LET variable
"LAMBDA(x,y,x-y)(Sheet1!$A$1+0,Sheet1!$B$1+0)",
]
.into_iter()
.enumerate()
{
let at = format!("D{}", i + 5);
t.set(&at, &format!("={f}"));
assert_eq!(t.get(&at), Value::Number(0.0), "{f}");
}
}
#[test]
fn a_lambda_body_uses_the_same_threshold_and_snaps_array_arguments_element_wise() {
// Observed on Windows Excel 16.0.20430 (review probe): 7 ulps snap, 8 ulps keep the residue, inside a body as in a cell.
let mut t = lambda_t();
t.put("G1", 1.0);
t.put("G2", 1.0 + 7.0 * ULP1);
t.put("G3", 1.0 + 8.0 * ULP1);
t.set("D5", "=LAMBDA(x,y,x-y)(Sheet1!$G$1,Sheet1!$G$2)");
t.set("D6", "=LAMBDA(x,y,x-y)(Sheet1!$G$1,Sheet1!$G$3)");
assert_eq!(t.get("D5"), Value::Number(0.0));
assert_eq!(t.get("D6"), Value::Number(-8.0 * ULP1));
// Array arguments: each element snaps by its own left operand (1 and 3 are different binades).
t.put("E1", 1.0);
t.put("E2", 3.0);
t.put("F1", 1.0 + ULP1);
t.put("F2", 3.0 + 2.0 * ULP1);
t.set("D8", "=INDEX(LAMBDA(x,y,x-y)(Sheet1!$E$1:$E$2,Sheet1!$F$1:$F$2),1,1)");
t.set("D9", "=INDEX(LAMBDA(x,y,x-y)(Sheet1!$E$1:$E$2,Sheet1!$F$1:$F$2),2,1)");
assert_eq!(t.get("D8"), Value::Number(0.0));
assert_eq!(t.get("D9"), Value::Number(0.0));
}
#[test]
fn a_lambda_that_calls_itself_ends_in_an_error_not_a_crash() {
// Which error depends on where the depth runs out first (#CALC! or #NAME?); what matters is that
// it ends. A recursion through cells is a separate, existing limit.
let mut t = lambda_t();
t.name("Loop", "LAMBDA(x,Loop(x)-1)");
t.set("D5", "=Loop(1)");
assert!(matches!(t.get("D5"), Value::Error(_)), "{:?}", t.get("D5"));
}
#[test]
fn trimrange() {
let mut t = T::new();
@@ -2035,6 +2593,65 @@ fn offset_extreme_arguments_return_ref() {
}
}
/// Sorting and ranking compare numbers exactly while `=` and COUNTIF compare them at 15
/// significant digits. Every expectation was observed in Excel 365 with these fixtures
/// (`=0.1+0.2` is 0.30000000000000004): 0.3 sorts first whatever the input order.
#[test]
fn sorts_and_ranks_compare_numbers_exactly() {
let mut t = T::new();
for (at, input) in [
// The noisy value first, then the exact one first.
("A1", "=0.1+0.2"),
("B1", "e"),
("A2", "0.3"),
("B2", "t"),
("D1", "0.3"),
("E1", "t"),
("D2", "=0.1+0.2"),
("E2", "e"),
("G1", "=100+1E-14"),
("H1", "e"),
("G2", "100"),
("H2", "t"),
] {
t.set(at, input);
}
let e = 0.1 + 0.2;
let n = Value::Number;
let s = |x: &str| Value::from(x);
let cases: Vec<(&str, Value)> = vec![
("=A1=A2", Value::Bool(true)),
("=COUNTIF(A1:A2,0.3)", n(2.0)),
("=INDEX(SORT(A1:B2),1,2)", s("t")),
("=INDEX(SORT(D1:E2),1,2)", s("t")),
("=INDEX(SORT(A1:B2,1,-1),1,2)", s("e")),
("=INDEX(SORT(D1:E2,1,-1),1,2)", s("e")),
("=INDEX(SORT(G1:H2),1,2)", s("t")),
("=INDEX(SORT(G1:H2,1,-1),1,2)", s("e")),
("=INDEX(SORTBY(B1:B2,A1:A2),1,1)", s("t")),
("=INDEX(SORTBY(E1:E2,D1:D2),1,1)", s("t")),
("=INDEX(SORTBY(B1:B2,A1:A2,-1),1,1)", s("e")),
("=INDEX(SORTBY(E1:E2,D1:D2,-1),1,1)", s("e")),
// Already exact: UNIQUE, RANK, LARGE/SMALL, MODE.
("=ROWS(UNIQUE(A1:A2))", n(2.0)),
("=RANK.EQ(0.3,A1:A2)", n(2.0)),
("=RANK.EQ(0.3,A1:A2,1)", n(1.0)),
("=RANK.AVG(0.3,A1:A2)", n(2.0)),
("=RANK.EQ(0.3,A1)", Value::Error(CellError::NA)),
("=LARGE(A1:A2,1)", n(e)),
("=SMALL(A1:A2,1)", n(0.3)),
("=MODE.SNGL(A1:A2,5)", Value::Error(CellError::NA)),
];
let mut wrong = Vec::new();
for (formula, expected) in cases {
let got = crate::evaluate(&t.wb, 0, c("Z1"), formula);
if got != expected {
wrong.push(format!("{formula}: got {got:?}, Excel {expected:?}"));
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// `@` intersects a reference with the formula's row (a column range) or column (a row range);
/// a 2D range both (circular when it includes the formula's cell); a range the formula does not
/// line up with gives #VALUE!. An array gives its top-left value. Legacy formulas read from files use it where Excel intersects implicitly.
@@ -2617,6 +3234,19 @@ fn loan_schedule_residue_keeps_excels_sign() {
assert_eq!(t.get("P7"), Value::Text("".into()));
}
#[test]
fn concat_operator_cuts_at_the_cell_limit() {
// Excel: LEN(REPT("x",20000)&REPT("x",20000)) is 32767, and REPT("x",32767)&"y" is 32767.
let mut t = T::new();
t.set("A1", "=LEN(REPT(\"x\",20000)&REPT(\"x\",20000))");
t.set("A2", "=LEN(REPT(\"x\",32767)&\"y\")");
t.set("A3", "=LEN(\"é\"&REPT(\"é\",32767))");
t.set("A4", "=LEN(REPT(UNICHAR(128512),16383)&\"x\")");
t.set("A5", "=LEN(REPT(UNICHAR(128512),16384))");
assert_eq!((t.num("A1"), t.num("A2"), t.num("A3"), t.num("A4")), (32767.0, 32767.0, 32767.0, 16384.0));
assert_eq!(t.get("A5"), Value::Error(CellError::Value));
}
#[test]
fn clearing_a_cell_unblocks_the_arrays_above_and_left_of_it() {
let mut t = T::new();
@@ -2880,13 +3510,17 @@ fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() {
let check = |wb: &Workbook, when: &str| {
let sh = wb.sheet(0).unwrap();
for (cell, f, lead, blocks) in &oracle {
let (mut sum, mut count, mut error) = (lead.unwrap_or(0.0), u64::from(lead.is_some()), None);
let (mut nums, mut count, mut error) = (Vec::new(), 0u64, None);
if let Some(l) = *lead {
nums.push(l);
count += 1;
}
for &(r0, c0, r1, c1) in blocks {
for r in r0..=r1 {
for col in c0..=c1 {
match sh.value(CellRef::new(r, col)) {
Value::Number(n) => {
sum += n;
nums.push(n);
count += 1;
}
Value::Error(e) if *f != "COUNT" => error = error.or(Some(e)),
@@ -2895,12 +3529,15 @@ fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() {
}
}
}
// SUM snaps only its last addition, matching Acc::finish. AVERAGE and the
// running total use the unsapped left-to-right fold.
let plain = nums.iter().fold(0.0, |a, n| a + n);
let want = match (error, *f) {
(Some(e), _) => Value::Error(e),
(_, "SUM") => Value::number(sum),
(_, "SUM") => Value::number(gridcraft_core::arith::sum_snapped(&nums)),
(_, "COUNT") => Value::number(count as f64),
(_, _) if count == 0 => Value::Error(CellError::Div0),
_ => Value::number(sum / count as f64),
_ => Value::number(plain / count as f64),
};
let got = sh.value(*cell);
let same = match (&got, &want) {
@@ -0,0 +1,17 @@
use gridcraft_calc::is_known_function;
use gridcraft_formula::FormulaLocale;
use std::collections::HashSet;
#[test]
fn every_polish_name_belongs_to_a_known_function() {
let names = FormulaLocale::Pl.aliases();
assert!(names.len() > 400, "{}", names.len());
let mut seen = HashSet::new();
for (en, pl) in names {
assert!(is_known_function(en), "{en} is not a GridCraft function");
assert_ne!(en, pl, "{en} needs no alias");
// A Polish name that is another function's English name would call the wrong function.
assert!(!is_known_function(pl), "{pl} ({en}) shadows an English function");
assert!(seen.insert(pl.to_uppercase()), "{pl} is listed twice");
}
}
+42 -15
View File
@@ -16,6 +16,7 @@ enum Fam {
Col100,
Line,
LineStack,
Line100,
Area,
AreaStack,
Area100,
@@ -31,6 +32,7 @@ fn family(k: ChartKind) -> Fam {
ColumnStacked100 | BarStacked100 => Fam::Col100,
Line | LineMarkers | Scatter | ScatterLines | Radar | Stock => Fam::Line,
LineStacked => Fam::LineStack,
LineStacked100 | LineStacked100Markers => Fam::Line100,
Area => Fam::Area,
AreaStacked => Fam::AreaStack,
AreaStacked100 => Fam::Area100,
@@ -40,7 +42,7 @@ fn family(k: ChartKind) -> Fam {
/// Families stacked to 100%: each category's values are shares of its total.
fn is_100(f: Fam) -> bool {
matches!(f, Fam::Col100 | Fam::Area100)
matches!(f, Fam::Col100 | Fam::Line100 | Fam::Area100)
}
fn is_col(f: Fam) -> bool {
@@ -48,7 +50,21 @@ fn is_col(f: Fam) -> bool {
}
fn is_line(f: Fam) -> bool {
matches!(f, Fam::Line | Fam::LineStack)
matches!(f, Fam::Line | Fam::LineStack | Fam::Line100)
}
/// Line kinds that draw a marker at each point.
fn has_markers(k: ChartKind) -> bool {
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
}
/// Stroke widths for explicitly selected Excel chart styles.
fn line_style_width(style: u32) -> f32 {
match style {
1 => 3.0,
9 => 5.0,
_ => 2.25,
}
}
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
@@ -64,6 +80,7 @@ struct BarRun {
}
impl BarRun {
/// Starts a single-bar run at `pos` spanning `lo..hi`.
fn new(pos: f32, lo: f32, hi: f32) -> Self {
BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi, merged: false }
}
@@ -71,6 +88,7 @@ impl BarRun {
fn touches(&self, lo: f32, hi: f32) -> bool {
lo <= self.hi && hi >= self.lo
}
/// Extends the merged run to cover `pos` and `lo..hi`.
fn add(&mut self, pos: f32, lo: f32, hi: f32) {
self.merged = true;
self.a0 = self.a0.min(pos);
@@ -105,13 +123,15 @@ struct BarSink {
bw: f32,
horizontal: bool,
color: Rgba,
stroke: Option<(Rgba, f32)>,
nslots: f32,
k: f32,
}
impl BarSink {
fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self {
BarSink { run: None, bw, horizontal, color, nslots, k }
/// Creates a bar emitter for series slot `k` of `nslots`.
fn new(bw: f32, horizontal: bool, color: Rgba, stroke: Option<(Rgba, f32)>, nslots: f32, k: f32) -> Self {
BarSink { run: None, bw, horizontal, color, stroke, nslots, k }
}
/// Start of this series' slot along the category axis, for the category centered at `c`.
fn pos(&self, c: f32) -> f32 {
@@ -131,11 +151,10 @@ impl BarSink {
let pos = self.pos(c);
let band = self.band();
if !merge {
if self.horizontal {
ctx.rect(lo, pos, len, self.bw, self.color, None);
} else {
ctx.rect(pos, lo, self.bw, len, self.color, None);
}
let (x, y, w, h) = if self.horizontal { (lo, pos, len, self.bw) } else { (pos, lo, self.bw, len) };
// Omit the outline when a bar is no wider/taller than the stroke, so the inner fill never disappears.
let stroke = self.stroke.filter(|(_, sw)| w > *sw && h > *sw);
ctx.rect(x, y, w, h, self.color, stroke);
return;
}
match &mut self.run {
@@ -147,6 +166,7 @@ impl BarSink {
}
}
}
/// Flushes any pending hairline bar run at the end of the series.
fn finish(self, ctx: &mut Ctx) {
let band = self.band();
if let Some(m) = self.run {
@@ -156,7 +176,7 @@ impl BarSink {
}
fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Vec<Vec<Option<(f64, f64)>>> {
// Totals for 100% stacking, per axis and family (100% columns and 100% areas stack apart).
// Totals for 100% stacking, per axis and family (100% columns, lines and areas stack apart).
let mut totals: Vec<((bool, Fam), Vec<f64>)> = Vec::new();
for (i, s) in data.series.iter().enumerate() {
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
@@ -187,7 +207,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
for (i, s) in data.series.iter().enumerate() {
let fam = fams.get(i).copied().unwrap_or(Fam::Col);
let a = sec.get(i).copied().unwrap_or(false);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::Line100 | Fam::AreaStack | Fam::Area100);
let key = (a, fam);
let si = if stacked {
match stacks.iter().position(|(k, _, _)| *k == key) {
@@ -216,7 +236,7 @@ fn series_spans(data: &ChartData, fams: &[Fam], sec: &[bool], ncat: usize) -> Ve
}),
(Some((_, pos, _)), _) => {
let v = v.unwrap_or(0.0);
let v = if fam == Fam::Area100 { share(key, j, v) } else { v };
let v = if is_100(fam) { share(key, j, v) } else { v };
pos.get_mut(j).map(|acc| {
let base = *acc;
*acc = clean(*acc + v);
@@ -287,6 +307,12 @@ fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec<usize>, f32) {
(slot_of, slot_keys.len().max(1) as f32)
}
/// Renders Cartesian column, bar, line, area, and combination charts.
///
/// Resolves series families and their axes, calculates stacking and
/// category positions, and draws the corresponding primitives.
/// Explicit chart style 9 adds white outlines to column and bar
/// rectangles, including stacked and 100%-stacked variants.
pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) {
let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS);
if ncat == 0 {
@@ -385,7 +411,8 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
let k = slot_of.get(i).copied().unwrap_or(0) as f32;
// Hairline bars are merged per pixel column (their envelope is what shows).
let cull = merge_hairlines(bw, labels_on);
let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k);
let stroke = (chart.style == 9).then_some((WHITE, 1.0));
let mut sink = BarSink::new(bw, horizontal, s.color, stroke, nslots, k);
for (j, sp) in row.iter().enumerate() {
let Some((b, t)) = sp else { continue };
let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc));
@@ -422,9 +449,9 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
}
_ => {
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
draw_runs(ctx, &pts, s.color, line_style_width(chart.style), s.smooth.then_some(plot));
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
if k == ChartKind::LineMarkers && cw >= 3.0 {
if has_markers(k) && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
}
if labels_on {
+4 -2
View File
@@ -57,8 +57,10 @@ pub fn legend_entries(chart: &Chart, data: &ChartData) -> Vec<(String, Rgba, Swa
.clone()
.map(|s| {
let sw = match s.kind {
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => {
Swatch::Line
}
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Scatter | ChartKind::Bubble => Swatch::Marker,
_ => Swatch::Box,
};
+2 -2
View File
@@ -71,8 +71,8 @@ pub(super) fn draw(ctx: &mut Ctx, chart: &Chart, data: &ChartData, plot: Bx, lay
let name_x = if settings.show_keys { x0 + 25.0 } else { x0 + 4.0 };
if settings.show_keys {
let swatch = match series.kind {
ChartKind::Line | ChartKind::LineStacked => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked | ChartKind::LineStacked100 => Swatch::Line,
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
_ => Swatch::Box,
};
draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color);
+90 -11
View File
@@ -39,6 +39,28 @@ pub fn series_color(theme: &Theme, i: usize) -> Rgba {
[r, g, b, 0xFF]
}
/// Excel reference colours for explicit styles 1 and 9.
///
/// These palettes cover measured default-theme examples.
/// Other counts still use the existing theme-based fallback.
fn chart_style_series_color(theme: &Theme, style: u32, index: usize, count: usize) -> Rgba {
if !matches!(style, 1 | 9) {
return series_color(theme, index);
}
const SMALL: [u8; 4] = [0x61, 0xB3, 0x81, 0x50];
const MEDIUM: [u8; 8] = [0x55, 0x9E, 0x72, 0x46, 0x83, 0xC1, 0x9A, 0xC8];
const LARGE: [u8; 16] = [0x4F, 0x93, 0x6A, 0x40, 0x7A, 0xB4, 0x61, 0xB3, 0x81, 0x50, 0x95, 0xDA, 0xAF, 0xD2, 0xBA, 0xAA];
let shades: &[u8] = match count {
1..=4 => &SMALL,
5..=8 => &MEDIUM,
9..=16 => &LARGE,
_ => return series_color(theme, index),
};
shades.get(index).map_or_else(|| series_color(theme, index), |shade| [*shade, *shade, *shade, 0xFF])
}
/// The first `n` series colours for `theme`.
pub fn default_palette(theme: &Theme, n: usize) -> Vec<Rgba> {
(0..n.min(4096)).map(|i| series_color(theme, i)).collect()
@@ -360,7 +382,7 @@ fn category_label(wb: &Workbook, src: Option<(&gridcraft_model::Sheet, RangeRef)
/// the outer levels of a multi-level axis: a category range wider than a column of values (or
/// taller than a row of values) groups its innermost labels, year beside month. Each outer level
/// has one entry per category, non-empty where a group starts, as the cells are.
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize) -> (Vec<String>, Vec<Vec<String>>) {
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize, innermost: bool) -> (Vec<String>, Vec<Vec<String>>) {
let cells: Option<(usize, RangeRef)> = parse_ref(wb, sheet, formula);
let value_range = parse_ref(wb, sheet, values).map(|(_, r)| r);
// Bound the category dimension by `limit` and read only the cells the levels use (the
@@ -419,12 +441,21 @@ fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limi
let at = |row: usize, col: usize| texts.get(row * w + col).cloned().unwrap_or_default();
let column = |c: usize| (0..h).map(|row| at(row, c)).collect::<Vec<String>>();
let row = |rr: usize| (0..w).map(|c| at(rr, c)).collect::<Vec<String>>();
let outer = levels.outer as usize;
if levels.by_columns {
let value_count = eval_list_in(wb, sheet, values, limit, 0).len();
let by_columns = if value_count == h && w > 1 && h != w {
true
} else if value_count == w && h > 1 && h != w {
false
} else {
levels.by_columns
};
let outer = if by_columns { w.saturating_sub(1).min(3) } else { h.saturating_sub(1).min(3) };
let result = if by_columns {
(column(w - 1), (1..=outer).filter_map(|k| (w - 1).checked_sub(k)).map(column).collect())
} else {
(row(h - 1), (1..=outer).filter_map(|k| (h - 1).checked_sub(k)).map(row).collect())
}
};
if innermost { (result.0, vec![]) } else { result }
}
/// Whether `t` names a defined name seen from `sheet` (`Name`, or `Sheet1!Name` looked up on
@@ -461,8 +492,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() {
let values = nums(wb, sheet, &s.values, limit);
let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1));
let color =
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
let color = s
.color
.as_ref()
.and_then(|c| c.resolve(&wb.theme))
.map(|[r, g, b]| [r, g, b, 0xFF])
.unwrap_or_else(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES)));
let kind = chart.series_kind(i);
let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) {
// X values with text in them (labels) are ignored: the points are numbered 1..n.
@@ -474,7 +509,7 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
if categories.is_none()
&& let Some(f) = &s.categories
{
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit);
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit, s.innermost_categories);
c.truncate(limit);
if !c.is_empty() {
categories = Some(c);
@@ -502,15 +537,59 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
secondary: s.secondary,
smooth: s.smooth,
trendlines,
number_format: ref_format(wb, sheet, &s.values),
number_format: match &s.number_format {
Some(code) if s.values.trim_start().starts_with('{') => code.clone(),
_ => ref_format(wb, sheet, &s.values),
},
});
}
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect());
let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE));
let palette = if matches!(chart.style, 1 | 9) {
(0..n.min(PALETTE_CYCLE)).map(|i| chart_style_series_color(&wb.theme, chart.style, i, n)).collect()
} else {
default_palette(&wb.theme, n.min(PALETTE_CYCLE))
};
ChartData { categories, category_levels, series, palette }
}
#[cfg(test)]
mod explicit_style_palette_tests {
use super::*;
/// Verifies grayscale palette selection and fallback boundaries for explicit styles 1 and 9.
#[test]
fn explicit_style_palette_boundaries() {
let theme = Workbook::default().theme;
for style in [1, 9] {
for count in [0, 17, 255] {
for index in [0, 1, 4, 8, 16] {
assert_eq!(chart_style_series_color(&theme, style, index, count), series_color(&theme, index));
}
}
for (count, expected_first) in [(1, 0x61), (4, 0x61), (5, 0x55), (8, 0x55), (9, 0x4F), (16, 0x4F)] {
assert_eq!(
chart_style_series_color(&theme, style, 0, count),
[expected_first, expected_first, expected_first, 255],
"style {style}, count {count}",
);
assert_eq!(
chart_style_series_color(&theme, style, 16, count),
series_color(&theme, 16),
"out-of-range index for style {style}, count {count}",
);
}
}
for style in [0, 2, 10, 48] {
assert_eq!(chart_style_series_color(&theme, style, 0, 4), series_color(&theme, 0));
}
}
}
#[cfg(test)]
mod label_budget_tests {
use gridcraft_model::Workbook;
@@ -521,7 +600,7 @@ mod label_budget_tests {
#[test]
fn category_labels_share_one_byte_budget() {
let wb = Workbook::new();
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS);
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS, false);
assert_eq!(texts.len(), 100_000);
assert_eq!(texts.first().map(String::len), Some(super::MAX_LABEL_CHARS));
assert!(texts.iter().map(String::len).sum::<usize>() <= super::MAX_CATEGORY_BYTES);
@@ -544,7 +623,7 @@ mod label_budget_tests {
}
}
// Five columns: column A is a fourth outer level and is discarded.
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS);
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS, false);
assert_eq!(outer.len(), 3);
assert_eq!(inner.last().map(String::len), Some(super::MAX_LABEL_CHARS));
assert_eq!(outer.first().and_then(|l| l.last()).map(String::len), Some(super::MAX_LABEL_CHARS));
+345 -1
View File
@@ -8,7 +8,7 @@ use crate::*;
mod budget;
mod data_table;
const ALL_KINDS: [ChartKind; 26] = [
const ALL_KINDS: [ChartKind; 28] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -18,6 +18,8 @@ const ALL_KINDS: [ChartKind; 26] = [
ChartKind::Line,
ChartKind::LineMarkers,
ChartKind::LineStacked,
ChartKind::LineStacked100,
ChartKind::LineStacked100Markers,
ChartKind::Pie,
ChartKind::Doughnut,
ChartKind::Area,
@@ -549,6 +551,9 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
// References use their cells' format, whatever the series says.
number_format: Some("0%".into()),
innermost_categories: false,
},
Series {
name: None,
@@ -561,6 +566,8 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: Some("Literal".into()),
@@ -573,6 +580,8 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: Some("0.0%".into()),
innermost_categories: false,
},
];
let d = resolve(&wb, 0, &c);
@@ -592,6 +601,7 @@ fn resolve_from_workbook() {
assert!(s1.secondary);
assert_eq!(d.series[2].name, "Literal");
assert_eq!(d.series[2].values.len(), 4);
assert_eq!(d.series[2].number_format, "0.0%");
// Default categories.
c.series.remove(0);
@@ -612,6 +622,8 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: None,
@@ -624,6 +636,8 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
];
let d = resolve(&wb, 0, &c);
@@ -641,6 +655,8 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series[0].x.as_ref().map(|x| x.len()), Some(3));
@@ -659,6 +675,8 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 7, &c);
assert_eq!(d.series.len(), 1);
@@ -1364,6 +1382,8 @@ fn pie_points_follow_workbook_theme() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
}];
let d = resolve(&wb, 0, &c);
let expected = vec![series_color(&wb.theme, 0), series_color(&wb.theme, 1)];
@@ -1419,6 +1439,47 @@ fn area_charts_draw_source_value_labels_only_when_enabled() {
}
}
#[test]
fn a_multi_level_category_block_draws_its_innermost_level() {
// A PivotChart's two levels of row labels in A1:B4, the outer one (country) on the left:
// one label per point, from the innermost column.
let mut wb = Workbook::new();
{
let s = wb.sheet_mut(0).unwrap();
s.name = "Graph".into();
for (r, (outer, inner)) in [("Canada", "Ottawa"), ("", "Toronto"), ("USA", "Boston"), ("", "NYC")].iter().enumerate() {
if !outer.is_empty() {
s.set_value(CellRef::new(r as u32, 0), Value::from(*outer));
}
s.set_value(CellRef::new(r as u32, 1), Value::from(*inner));
s.set_value(CellRef::new(r as u32, 2), Value::Number(r as f64 + 1.0));
s.set_value(CellRef::new(5, r as u32), Value::from(*inner));
s.set_value(CellRef::new(6, r as u32), Value::from(*outer));
}
}
let mut c = chart(ChartKind::ColumnClustered);
c.series = vec![Series {
categories: Some("Graph!$A$1:$B$4".into()),
values: "Graph!$C$1:$C$4".into(),
innermost_categories: true,
..Series::default()
}];
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
// A block with a column per point: its last row is the innermost level.
c.series[0].categories = Some("Graph!$A$6:$D$7".into());
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Canada", "", "USA", ""]);
assert!(data.category_levels.is_empty(), "innermost PivotChart must not expose outer labels");
// Without the flag, every cell is a label, as for any other chart.
c.series[0].categories = Some("Graph!$A$1:$B$4".into());
c.series[0].innermost_categories = false;
let data = resolve(&wb, 0, &c);
assert_eq!(data.categories, vec!["Ottawa", "Toronto", "Boston", "NYC"]);
assert_eq!(data.category_levels, vec![vec!["Canada", "", "USA", ""]]);
}
#[test]
fn drawing_and_resolving_agree_on_the_combo_plot_kind() {
// Resolved series carry `Chart::series_kind`, the kind drawing uses: for every chart kind,
@@ -1491,6 +1552,62 @@ fn hundred_percent_stacked_areas_fill_each_category_to_its_total() {
assert!(frac(top(south, 2)).abs() < 1e-3, "Q3: South reaches {}", frac(top(south, 2)));
}
#[test]
fn hundred_percent_stacked_lines_end_each_category_at_its_total() {
let (north_color, south_color) = ([20, 96, 130, 255], [25, 107, 36, 255]);
for kind in [ChartKind::LineStacked100, ChartKind::LineStacked100Markers] {
let d = ChartData {
category_levels: vec![],
palette: vec![],
categories: ["Q1", "Q2", "Q3", "Q4"].iter().map(|s| s.to_string()).collect(),
series: vec![series("North", &[10.0, 30.0, 0.0, 5.0], north_color, kind), series("South", &[30.0, 10.0, 0.0, 15.0], south_color, kind)],
};
let mut c = chart(kind);
c.data_labels = false;
let p = render(&c, &d, 640.0, 400.0, &ApproxMeasure);
let t = texts(&p);
assert!(t.contains(&"100%") && t.contains(&"0%"), "{kind:?}: {t:?}");
assert!(!t.contains(&"40"), "{kind:?}: {t:?}");
// The value axis labels sit on their gridlines.
let label_y = |s: &str| {
p.iter()
.find_map(|p| match p {
Prim::Text { text, y, .. } if text == s => Some(*y),
_ => None,
})
.unwrap_or(f32::NAN)
};
let (y0, y100) = (label_y("0%"), label_y("100%"));
assert!(y0 > y100, "{kind:?}: {y0} {y100}");
let frac = |y: f32| (y0 - y) / (y0 - y100);
let line = |color: Rgba| {
p.iter()
.find_map(|p| match p {
// The series line is 2.25 wide; its legend swatch is 2.0.
Prim::Line { pts, color: c, width, .. } if *c == color && *width > 2.1 => {
Some(pts.iter().map(|q| frac(q[1])).collect::<Vec<f32>>())
}
_ => None,
})
.unwrap_or_default()
};
let (north, south) = (line(north_color), line(south_color));
assert_eq!((north.len(), south.len()), (4, 4), "{kind:?}: {north:?} {south:?}");
// A category whose total is zero stays on the baseline.
for (j, (n, s)) in [(0.25, 1.0), (0.75, 1.0), (0.0, 0.0), (0.25, 1.0)].into_iter().enumerate() {
assert!((north[j] - n).abs() < 1e-3 && (south[j] - s).abs() < 1e-3, "{kind:?} Q{}: {} {}", j + 1, north[j], south[j]);
}
// Point markers have a white outline; the legend's marker swatches have none.
let circles = |outlined: bool| {
p.iter()
.filter(|p| matches!(p, Prim::Circle { fill: Some(f), stroke, .. } if (*f == north_color || *f == south_color) && stroke.is_some() == outlined))
.count()
};
let with_markers = kind == ChartKind::LineStacked100Markers;
assert_eq!((circles(true), circles(false)), if with_markers { (8, 2) } else { (0, 0) }, "{kind:?}");
}
}
#[test]
fn two_level_categories_resolve_and_draw() {
let years = ["2023", "", "", "2024", "", ""];
@@ -1565,6 +1682,22 @@ fn two_level_categories_resolve_and_draw() {
assert!(d.category_levels.is_empty());
}
#[test]
fn square_category_blocks_keep_their_declared_orientation_on_ties() {
let mut wb = Workbook::new();
let s = wb.sheet_mut(0).unwrap();
s.name = "Data".into();
for (i, value) in ["A1", "B1", "A2", "B2", "A3", "B3"].iter().enumerate() {
s.set_value(CellRef::parse(value).unwrap(), Value::from(*value));
s.set_value(CellRef::new(3, i as u32), Value::Number(i as f64 + 1.0));
}
let mut c = chart(ChartKind::Line);
c.series = vec![Series { categories: Some("Data!$A$1:$B$2".into()), values: "Data!$A$3:$B$3".into(), ..Series::default() }];
let d = resolve(&wb, 0, &c);
assert_eq!(d.categories, vec!["A2", "B2"]);
assert_eq!(d.category_levels, vec![vec!["A1", "B1"]]);
}
#[test]
fn a_huge_trendline_forecast_does_not_collapse_the_columns() {
let m = ApproxMeasure;
@@ -1610,6 +1743,7 @@ fn box_whisker_draws_each_series_quartile_method() {
assert!((heights[0] / heights[1] - 1.4).abs() < 0.001);
}
/// Defined-name series titles on sheets with apostrophes resolve properly.
#[test]
fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
// #2012: `'Bob''s'!Title` kept the doubled quote, so the sheet wasn't found and the series
@@ -1641,11 +1775,13 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
..Series::default()
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
}
/// Defined-name series titles on sheets whose names contain `!` resolve properly.
#[test]
fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
// `'a!b'!Title`: the sheet name holds a `!`, so the evaluator must split the parsed name at
@@ -1677,11 +1813,13 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
..Series::default()
}];
let d = resolve(&wb, 0, &c);
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
}
/// Volatile functions in series values or names mark the chart as volatile.
#[test]
fn volatile_series_formulas_are_detected() {
let wb = Workbook::new();
@@ -1698,6 +1836,8 @@ fn volatile_series_formulas_are_detected() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
@@ -1712,6 +1852,7 @@ fn volatile_series_formulas_are_detected() {
assert!(!has_volatile_series(&wb, 0, &chart(ChartKind::Line)));
}
/// Defined names referenced by series formulas are followed for volatility checks.
#[test]
fn volatile_defined_names_are_followed() {
let with = |values: &str| {
@@ -1727,6 +1868,8 @@ fn volatile_defined_names_are_followed() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
@@ -1774,3 +1917,204 @@ fn volatile_defined_names_are_followed() {
assert!(!has_volatile_series(&wb, 1, &with("=Dice")));
assert!(has_volatile_series(&wb, 1, &with("=FreshClock")));
}
/// Explicit Excel chart styles should affect default series colours,
/// without changing the workbook theme.
#[test]
fn explicit_chart_styles_use_distinct_default_colors() {
let wb = Workbook::default();
let mut c = chart(ChartKind::ColumnClustered);
c.series.push(Series { values: "{10,20,30}".into(), ..Series::default() });
c.style = 2;
let style2 = resolve(&wb, 0, &c).series[0].color;
assert_eq!(style2, series_color(&wb.theme, 0));
c.style = 1;
let style1 = resolve(&wb, 0, &c).series[0].color;
c.style = 9;
let style9 = resolve(&wb, 0, &c).series[0].color;
assert_ne!(style1, style2, "style 1 should differ from style 2");
assert_ne!(style9, style2, "style 9 should differ from style 2");
}
/// Excel chart styles must not override explicitly assigned series colours.
#[test]
fn explicit_chart_styles_preserve_custom_series_colors() {
let wb = Workbook::default();
let mut c = chart(ChartKind::ColumnClustered);
c.series.push(Series { values: "{10,20,30}".into(), color: Some(Color::rgb(12, 34, 56)), ..Series::default() });
for style in [1, 2, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
assert_eq!(data.series[0].color, [12, 34, 56, 255], "explicit series colour changed under chart style {style}");
}
}
/// Check the first four point colours measured in Excel for styles 1 and 9.
#[test]
fn excel_chart_styles_use_measured_point_palette() {
let wb = Workbook::default();
let mut c = chart(ChartKind::Pie);
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]];
for style in [1, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
assert_eq!(&data.palette[..4], &expected);
assert_eq!(data.series[0].color, expected[0]);
}
}
/// Excel's default-theme chart colours depend on the total series count.
#[test]
fn excel_chart_styles_depend_on_series_count() {
let wb = Workbook::default();
let base_series = Series { values: "{10,20,30,40}".into(), ..Series::default() };
let cases: &[(usize, [[u8; 4]; 3])] = &[
(6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]),
(12, [[0x4F, 0x4F, 0x4F, 0xFF], [0x93, 0x93, 0x93, 0xFF], [0x6A, 0x6A, 0x6A, 0xFF]]),
];
for (count, expected) in cases {
for style in [1, 9] {
let mut c = chart(ChartKind::ColumnClustered);
c.style = style;
c.series = vec![base_series.clone(); *count];
let data = resolve(&wb, 0, &c);
assert_eq!(data.series.len(), *count);
for (i, color) in expected.iter().enumerate() {
assert_eq!(data.series[i].color, *color, "style {style}, {count} series, index {i}");
}
}
}
}
/// Style 9 uses white outlines on column and bar data rectangles.
#[test]
fn explicit_style_nine_draws_white_column_outlines() {
let wb = Workbook::default();
for kind in [
ChartKind::ColumnClustered,
ChartKind::BarClustered,
ChartKind::ColumnStacked,
ChartKind::BarStacked,
ChartKind::ColumnStacked100,
ChartKind::BarStacked100,
] {
let mut c = chart(kind);
c.legend = LegendPos::None;
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
for style in [1, 2, 9] {
c.style = style;
let data = resolve(&wb, 0, &c);
let color = data.series[0].color;
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
let outlines: Vec<_> = prims
.iter()
.filter_map(|p| match p {
Prim::Rect { fill: Some(fill), stroke, .. } if *fill == color => Some(*stroke),
_ => None,
})
.collect();
assert!(!outlines.is_empty(), "No data rectangles for {kind:?}, style {style}");
let expected = if style == 9 { Some(([255, 255, 255, 255], 1.0)) } else { None };
assert!(outlines.iter().all(|stroke| *stroke == expected), "Unexpected outline for {kind:?}, style {style}: {outlines:?}");
}
}
}
/// Excel's default line weights are 3 pt for style 1 and 5 pt for style 9.
/// Other styles retain GridCraft's existing stroke width.
#[test]
fn explicit_excel_styles_set_line_stroke_width() {
let color: Rgba = [17, 73, 131, 255];
for kind in [ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked] {
let data = ChartData {
categories: ["Jan", "Feb", "Mar", "Apr"].map(String::from).to_vec(),
category_levels: vec![],
palette: vec![],
series: vec![series("North", &[12.0, 19.0, 25.0, 30.0], color, kind)],
};
let mut c = chart(kind);
c.legend = LegendPos::None;
c.data_labels = false;
for (style, expected_width) in [(0, 2.25_f32), (1, 3.0), (2, 2.25), (9, 5.0), (48, 2.25)] {
c.style = style;
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
let widths: Vec<f32> = prims
.iter()
.filter_map(|primitive| match primitive {
Prim::Line { color: line_color, width, .. } if *line_color == color => Some(*width),
_ => None,
})
.collect();
assert_eq!(widths, vec![expected_width], "Unexpected stroke width for {kind:?}, style {style}");
}
}
}
/// Narrow style 9 bars (at or below the 1 px outline width) omit the white stroke so their gray fill stays visible.
#[test]
fn narrow_style_9_bars_retain_visible_fill() {
let fill_color: Rgba = [0x61, 0x61, 0x61, 0xFF];
// Stay within MAX_LABELS (200) so data labels remain active on the direct unmerged path,
// while keeping each single-series slot <= 0.88 px inside the 220 px chart.
let count = 100usize;
let categories: Vec<String> = (0..count).map(|i| format!("C{i}")).collect();
let values = vec![50.0; count];
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] {
let data = ChartData {
categories: categories.clone(),
category_levels: vec![],
palette: vec![],
series: vec![series("S1", &values, fill_color, kind)],
};
let mut c = chart(kind);
c.legend = LegendPos::None;
// Data labels keep bars on the unmerged direct path even when narrower than 1 px.
c.data_labels = true;
c.gridlines = false;
c.style = 9;
let prims = render(&c, &data, 220.0, 220.0, &ApproxMeasure);
let narrow_bars: Vec<_> = prims
.iter()
.filter_map(|p| match p {
Prim::Rect { w, h, fill: Some(fill), stroke, .. } if *fill == fill_color && (*w <= 1.0 || *h <= 1.0) => Some(*stroke),
_ => None,
})
.collect();
assert_eq!(narrow_bars.len(), count, "Direct unmerged path must emit all {count} bars individually for {kind:?}");
assert!(narrow_bars.iter().all(Option::is_none), "Narrow style 9 bars must omit the 1 px white outline: {narrow_bars:?}");
}
}
+29
View File
@@ -148,3 +148,32 @@ fn dense_and_tiny_tables_are_bounded_and_explicit() {
assert_sane(&render(&c, &d, w, h, &ApproxMeasure), w, h);
}
}
#[test]
fn table_keys_for_100_percent_stacked_lines_use_line_swatches() {
for (kind, marker) in [(ChartKind::LineStacked100, false), (ChartKind::LineStacked100Markers, true)] {
let mut c = chart(kind);
c.title = Some(String::new());
c.legend = LegendPos::None;
c.data_labels = false;
c.data_table = Some(ChartDataTable::default());
let color = [1, 2, 3, 255];
let d = ChartData {
categories: ["Jan", "Feb"].map(String::from).to_vec(),
series: vec![series("Rate", &[1.0, 3.0], color, kind)],
..Default::default()
};
let p = render(&c, &d, 600.0, 400.0, &ApproxMeasure);
let header_y = p
.iter()
.find_map(|p| match p {
Prim::Text { text, y, .. } if text == "Jan" => Some(*y),
_ => None,
})
.unwrap();
let key_circles = p.iter().filter(|p| matches!(p, Prim::Circle { cy, fill: Some(f), .. } if *f == color && *cy > header_y)).count();
assert_eq!(key_circles, usize::from(marker), "{kind:?}");
let key_box = p.iter().any(|p| matches!(p, Prim::Rect { y, fill: Some(f), .. } if *f == color && *y > header_y));
assert!(!key_box, "{kind:?} key is a line swatch");
}
}
+29
View File
@@ -123,11 +123,27 @@ pub fn letters_to_col(s: &str) -> Option<u32> {
/// A rectangular block of cells, inclusive on both ends. Always normalised (`start <= end`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(from = "RangeRefFields")]
pub struct RangeRef {
pub start: CellRef,
pub end: CellRef,
}
/// A range as stored (`{start, end}`). A file may hold any numbers there, so loading puts the
/// corners in order and on the sheet: `height()` and `width()` subtract them unchecked (#2160).
#[derive(Deserialize)]
struct RangeRefFields {
start: CellRef,
end: CellRef,
}
impl From<RangeRefFields> for RangeRef {
fn from(r: RangeRefFields) -> Self {
let on_sheet = |c: CellRef| CellRef::new(c.row.min(MAX_ROWS - 1), c.col.min(MAX_COLS - 1));
RangeRef::new(on_sheet(r.start), on_sheet(r.end))
}
}
impl RangeRef {
pub fn new(a: CellRef, b: CellRef) -> Self {
RangeRef { start: CellRef::new(a.row.min(b.row), a.col.min(b.col)), end: CellRef::new(a.row.max(b.row), a.col.max(b.col)) }
@@ -337,6 +353,19 @@ mod tests {
assert_eq!(split_areas(""), [""]);
}
#[test]
fn a_loaded_range_is_ordered_and_on_the_sheet() {
// #2160: a file can hold any corners; `height()` subtracts them unchecked.
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":4000000000,"col":5},"end":{"row":2,"col":1}}"#).unwrap();
assert_eq!(r, RangeRef::new(CellRef::new(2, 1), CellRef::new(MAX_ROWS - 1, 5)));
assert_eq!((r.height(), r.width()), (MAX_ROWS - 2, 5));
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":9,"col":99999},"end":{"row":3,"col":0}}"#).unwrap();
assert_eq!(r, RangeRef::new(CellRef::new(3, 0), CellRef::new(9, MAX_COLS - 1)));
// What is saved loads back unchanged.
let ok = RangeRef::new(CellRef::new(1, 2), CellRef::new(7, 3));
assert_eq!(serde_json::from_str::<RangeRef>(&serde_json::to_string(&ok).unwrap()).unwrap(), ok);
}
#[test]
fn range_parse_rejects_signed_rows() -> Result<(), std::io::Error> {
assert!(RangeRef::parse("+1:+3").is_none());
+71
View File
@@ -0,0 +1,71 @@
//! Arithmetic that follows Excel's bits rather than IEEE's: the snap to zero.
/// 2^-49: the snap threshold is this fraction of the left operand's binade.
const SNAP: f64 = 1.0 / 562_949_953_421_312.0;
/// The power of two at the bottom of `x`'s binade (`x` with its mantissa cleared); 0 for zero,
/// subnormal and non-finite values.
fn binade(x: f64) -> f64 {
if x.is_finite() { f64::from_bits(x.to_bits() & 0x7FF0_0000_0000_0000) } else { 0.0 }
}
/// `x + y` as Excel computes it at the root of a formula or as the last addition of a `SUM`:
/// when the operands have opposite signs and `|x + y| < 2^(e-49)`, `e` the binary exponent of
/// the LEFT operand `x`, the result is exactly 0. A subtraction passes `-y`.
///
/// Excel does this only at those places, not at every add or subtract (observed on Windows Excel 16.0.20430; see
/// `EXCEL-BEHAVIOUR.md` of the Spreadsheet Accuracy Suite, "The snap to zero").
pub fn snap_add(x: f64, y: f64) -> f64 {
let s = x + y;
let opposite = (x > 0.0 && y < 0.0) || (x < 0.0 && y > 0.0);
if opposite && s.abs() < binade(x) * SNAP { 0.0 } else { s }
}
/// The sum of `values` left to right, each addition rounded, with the LAST addition snapped.
/// This is `SUM`'s arithmetic: `SUM(a, -b)` is 0 for a near-cancellation, but `SUM(a, -b, 0)` keeps
/// the residue because its last addition is residue + 0.
pub fn sum_snapped(values: &[f64]) -> f64 {
let Some((last, head)) = values.split_last() else { return 0.0 };
snap_add(head.iter().fold(0.0, |acc, v| acc + v), *last)
}
#[cfg(test)]
mod tests {
use super::*;
const ULP1: f64 = f64::EPSILON;
#[test]
fn snaps_below_two_to_the_e_minus_49_of_the_left_operand() {
assert_eq!(snap_add(1.0, -(1.0 + ULP1)), 0.0);
assert_eq!(snap_add(1.0, -(1.0 + 7.0 * ULP1)), 0.0);
// Exactly 2^-49 (8 ulps of 1.0) does not snap.
assert_eq!(snap_add(1.0, -(1.0 + 8.0 * ULP1)), -8.0 * ULP1);
// The left operand's binade decides (observed on Windows Excel 16.0.20430, excel-probe-4.00044 to 00046):
// 0.4999999999999998 - 0.5000000000000002 keeps -4.44e-16 (threshold 2^-51 is not beaten),
// the other way round it is 0 (threshold 2^-50).
assert_eq!(snap_add(0.4999999999999998, -0.5000000000000002), -4.440892098500626e-16);
assert_eq!(snap_add(0.5000000000000002, -0.4999999999999998), 0.0);
}
#[test]
fn never_snaps_same_sign_zero_or_hostile_operands() {
assert_eq!(snap_add(1e-20, 2e-20), 1e-20 + 2e-20);
assert_eq!(snap_add(3.0, 0.0), 3.0);
assert_eq!(snap_add(0.0, -1e-300), -1e-300);
// A subnormal left operand has no binade to measure against: it never snaps.
assert_eq!(snap_add(5e-324, -1e-323), -5e-324);
assert!(snap_add(f64::INFINITY, -f64::INFINITY).is_nan());
assert_eq!(snap_add(-1.0, 1.0 + ULP1), 0.0);
}
#[test]
fn sum_snaps_only_its_last_addition() {
assert_eq!(sum_snapped(&[]), 0.0);
assert_eq!(sum_snapped(&[1.0, -(1.0 + ULP1)]), 0.0);
assert_eq!(sum_snapped(&[1.0, -(1.0 + ULP1), 0.0]), 1.0 - (1.0 + ULP1));
assert_eq!(sum_snapped(&[3.0, 1e16, -1e16, 0.0]), 4.0);
// Left to right, each addition rounded: ten 0.1s do not make 1.
assert_eq!(sum_snapped(&[0.1; 10]), 0.999_999_999_999_999_9);
}
}
+65
View File
@@ -162,6 +162,43 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti
Some(serial as f64)
}
/// The calendar date a pivot cache's ISO 8601 date items (`<d>`, `minDate`, `startDate`…) give
/// a date of a date system's calendar, as [`datetime_from_serial`] returns it. Those dates count
/// real days: from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to
/// February 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious
/// 1900-02-29, runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30,
/// serial 1 is 1899-12-31 and serial 60 is 1900-02-28. Excel writes its caches that way.
pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) {
if sys == DateSystem::D1900 && year == 1900 && month <= 2 {
let serial = if month <= 1 { day } else { 31 + day };
return civil_from_days(i64::from(serial) + UNIX_1899_12_30);
}
(year, month, day)
}
/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`]
/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid.
/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the
/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date,
/// or one before the epoch or after 9999-12-31.
pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option<f64> {
let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?);
match (sys, y, m, d) {
(DateSystem::D1900, 1900, 2, 29) => return Some(60.0),
(DateSystem::D1904, 1899, 12, 30) => return Some(0.0),
_ => {}
}
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) {
return None;
}
let base = match sys {
DateSystem::D1900 => UNIX_1899_12_30,
DateSystem::D1904 => UNIX_1904_01_01,
};
let serial = days_from_civil(y, m, d) - base;
(0..=max_serial(sys)).contains(&serial).then_some(serial as f64)
}
/// Date/time from a serial. `None` for negative or too-large serials.
pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option<DateTime> {
if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) {
@@ -384,4 +421,32 @@ mod tests {
assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar
Ok(())
}
#[test]
fn iso_dates_count_real_days() {
let s = DateSystem::D1900;
// Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31.
for (serial, ymd) in
[(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))]
{
let d = datetime_from_serial(s, serial as f64).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}");
assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}");
}
assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None);
assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None);
assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0));
assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None);
assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None);
// The 1904 system has no offset; 1899-12-30 stands for a time's date part there too.
let s = DateSystem::D1904;
let d = datetime_from_serial(s, 0.5).unwrap();
assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1));
assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0));
assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0));
assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None);
}
}
+2 -1
View File
@@ -4,6 +4,7 @@
#![forbid(unsafe_code)]
pub mod addr;
pub mod arith;
pub mod color;
pub mod date;
pub mod parse;
@@ -16,4 +17,4 @@ pub use addr::{
};
pub use date::DateSystem;
pub use region::Region;
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
+26
View File
@@ -49,6 +49,19 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option<f64> {
parse_numeric(s.trim(), sys).map(|(n, _)| n)
}
/// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users
/// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5,
/// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse
/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. So does `+`
/// before a time (`+1:30`), while `-1:30` is a formula (rows 1 to 30), as Excel for the web does.
pub fn starts_formula(input: &str) -> bool {
input.starts_with('=')
|| (input.len() > 1
&& input.starts_with(['+', '-'])
&& parse_number_text(input).is_none()
&& !input.strip_prefix('+').is_some_and(|time| time.contains(':') && parse_number_text(time).is_some()))
}
/// Text that Excel's "Number Stored as Text" check flags: it would be a number if typed (signs,
/// thousands separators, currency, percent, exponent, a parenthesised negative). Dates, times and
/// fractions kept as text are not flagged, as in Excel.
@@ -577,6 +590,19 @@ mod tests {
assert_eq!(p("1.2.3.4").value, Value::text("1.2.3.4"));
}
#[test]
fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() {
// #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did.
for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--", "-1:30", "+1/30", "-1/30"] {
assert!(starts_formula(s), "{s}");
}
// Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or
// apostrophe, `+` before a time and other text stay text.
for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b", "+1:30", "+0:30:15"] {
assert!(!starts_formula(s), "{s}");
}
}
#[test]
fn dates_and_times() {
assert_eq!(p("10/7/2026").value, Value::Number(46302.0));
+94
View File
@@ -103,6 +103,10 @@ impl fmt::Display for CellError {
}
/// A 2-D array of values (row-major). Always at least 1×1.
///
/// Indexing assumes `data` holds `rows × cols` values. Loading doesn't check that (the fields are
/// public, so a file can say anything): whoever loads values from a file checks them with
/// [`Value::is_well_formed`] and repairs what fails (#2160).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Array {
pub rows: usize,
@@ -208,6 +212,23 @@ impl From<Array> for Value {
}
impl Value {
/// Whether every array in this value, including arrays nested in another array's values, is
/// at least 1×1 and holds exactly `rows × cols` values, as indexing assumes. Values built in
/// code always are; values loaded from a file may not be (#2160). Walks without recursion,
/// so a deeply nested value can't overflow the stack.
pub fn is_well_formed(&self) -> bool {
let mut pending = vec![self];
while let Some(v) = pending.pop() {
if let Value::Array(a) = v {
if a.rows == 0 || a.cols == 0 || a.rows.checked_mul(a.cols) != Some(a.data.len()) {
return false;
}
pending.extend(a.data.iter().filter(|x| matches!(x, Value::Array(_))));
}
}
true
}
/// A number, or `#NUM!` when it is NaN or infinite (Excel never stores those).
pub fn number(v: f64) -> Value {
if v.is_finite() { Value::Number(if v == 0.0 { 0.0 } else { v }) } else { Value::Error(CellError::Num) }
@@ -434,12 +455,16 @@ fn secondary_weights(s: &str) -> impl Iterator<Item = u16> + '_ {
}
/// Sorting order used by Sort (ascending): numbers, text, booleans, errors, then blanks last.
/// Numbers compare exactly, not at the 15 digits of [`compare`]. Observed in Excel 365: SORT,
/// SORTBY, Data > Sort, the AutoFilter sort and table sort all put 0.3 before `=0.1+0.2`
/// (0.30000000000000004) ascending and after it descending, whatever the input order.
pub fn sort_compare(a: &Value, b: &Value) -> Ordering {
match (a, b) {
(Value::Empty, Value::Empty) => Ordering::Equal,
(Value::Empty, _) => Ordering::Greater,
(_, Value::Empty) => Ordering::Less,
(Value::Error(_), Value::Error(_)) => Ordering::Equal,
(Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
_ => compare(a, b),
}
}
@@ -497,10 +522,56 @@ pub fn sci_text(n: f64, sig: usize) -> String {
format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs())
}
/// Longest text a cell can hold, in UTF-16 code units.
pub const MAX_TEXT_CHARS: usize = 32_767;
/// `s` cut to [`MAX_TEXT_CHARS`] UTF-16 code units without splitting a Unicode scalar value.
pub fn cap_text(mut s: String) -> String {
if s.len() > MAX_TEXT_CHARS {
let mut units = 0;
if let Some((i, _)) = s.char_indices().find(|(_, c)| {
units += c.len_utf16();
units > MAX_TEXT_CHARS
}) {
s.truncate(i);
}
}
s
}
/// `v` with text cut to [`MAX_TEXT_CHARS`] UTF-16 code units; other values pass through.
pub fn cap_value(v: Value) -> Value {
match v {
Value::Text(t) if t.len() > MAX_TEXT_CHARS => Value::text(cap_text(t.to_string())),
v => v,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_loaded_array_is_checked_by_is_well_formed() {
// #2160: indexing assumes `data.len() == rows * cols`. A file can say otherwise; loading
// keeps what it says and `is_well_formed` tells the loader to repair it.
let number = |n: f64| Value::Number(n);
let loaded = |json: &str| serde_json::from_str::<Value>(json).unwrap();
for bad in [
r#"{"t":"Array","v":{"rows":3,"cols":2,"data":[{"t":"Number","v":1.0}]}}"#,
r#"{"t":"Array","v":{"rows":0,"cols":1,"data":[]}}"#,
r#"{"t":"Array","v":{"rows":18446744073709551615,"cols":2,"data":[]}}"#,
// Nested in a well-formed array.
r#"{"t":"Array","v":{"rows":1,"cols":2,"data":[{"t":"Number","v":1.0},{"t":"Array","v":{"rows":2,"cols":2,"data":[]}}]}}"#,
] {
assert!(!loaded(bad).is_well_formed(), "{bad}");
}
let ok = Value::from(Array::new(1, 2, vec![number(1.0), Value::from(Array::scalar(number(2.0)))]).unwrap());
let back = loaded(&serde_json::to_string(&ok).unwrap());
assert_eq!(back, ok, "what is saved loads back unchanged");
assert!(back.is_well_formed() && number(1.0).is_well_formed() && Value::Empty.is_well_formed());
}
#[test]
fn number_text() {
assert_eq!(number_to_text(1.0), "1");
@@ -580,6 +651,16 @@ mod tests {
assert_eq!(sort_compare(&Value::Empty, &Value::Number(1.0)), Ordering::Greater);
}
#[test]
fn cap_text_uses_utf16_units_without_splitting_surrogate_pairs() {
let face = "😀";
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS)), "x".repeat(MAX_TEXT_CHARS));
assert_eq!(cap_text("x".repeat(MAX_TEXT_CHARS + 1)), "x".repeat(MAX_TEXT_CHARS));
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face)), format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 2), face));
assert_eq!(cap_text(format!("{}{}", "x".repeat(MAX_TEXT_CHARS - 1), face)), "x".repeat(MAX_TEXT_CHARS - 1));
assert_eq!(cap_text(face.repeat(16_384)), face.repeat(16_383));
}
#[test]
fn arabic_diacritics_sort_with_their_base_letter() {
assert_eq!(compare_text("بَاب", "بيت"), Ordering::Less);
@@ -775,6 +856,19 @@ mod tests {
assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less);
}
#[test]
fn sort_orders_numbers_exactly() {
let num = Value::Number;
let e = 0.1 + 0.2;
assert_eq!(sort_compare(&num(0.3), &num(e)), Ordering::Less);
assert_eq!(sort_compare(&num(e), &num(0.3)), Ordering::Greater);
assert_eq!(sort_compare(&num(100.0), &num(100.0 + 1e-14)), Ordering::Less);
assert_eq!(sort_compare(&num(0.0), &num(-0.0)), Ordering::Equal);
assert_eq!(sort_compare(&num(1.0), &Value::from("a")), Ordering::Less);
// `=` keeps its 15-digit comparison.
assert_eq!(compare(&num(0.3), &num(e)), Ordering::Equal);
}
#[test]
fn arrays() -> Result<(), std::io::Error> {
let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).ok_or_else(|| std::io::Error::other("valid array"))?;
+35
View File
@@ -0,0 +1,35 @@
[package]
name = "gridcraft-dax"
# A first release of this crate, not the workspace release line: nothing depends on a published
# version of it yet, and 0.1.0 says what it is — new.
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "GridCraft DAX language: lexer, Pratt parser, syntax tree and canonical printer"
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
# Calendar arithmetic (date serials, month lengths, leap years) goes through chrono on every
# target, as AGENTS.md requires. The web build has no clock and uses the fixed fallback in
# `eval/support.rs`, but the date types it needs build for wasm too (`gridcraft-core` does the
# same with the same workspace dependency).
chrono = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# The browser clock for NOW/TODAY under wasm, the same dependency `crates/core` uses: the standard
# library clock traps there, and `eval/support.rs` would otherwise freeze at 1970.
js-sys = "0.3"
[[example]]
name = "parse"
# Cargo does not test examples by default; this one carries assertions on the query-to-expression
# fallback, so it has to run under `cargo test`.
test = true
[dev-dependencies]
serde_json = { workspace = true }
+430
View File
@@ -0,0 +1,430 @@
# gridcraft-dax
The DAX language for GridCraft: a tokenizer, a Pratt parser, a syntax tree, a canonical printer,
the function catalog for every dax.guide category with static call validation, the static type surface (types,
literals, inference and operator result tables), the full DAX statement/query grammar, a model
evaluator, a columnar model store and a model-backed PivotTable renderer. It has no dependency on
the GridCraft engine.
```rust
use gridcraft_dax::{ParseError, parse_expression, print_expression};
fn main() -> Result<(), ParseError> {
let expr = parse_expression("1 + 2 * 3")?;
assert_eq!(print_expression(&expr), "1 + 2 * 3");
let query = gridcraft_dax::parse_query(
"DEFINE MEASURE Sales[Margin] = [Sales Amount] - [Total Cost] EVALUATE Sales ORDER BY [Margin] DESC",
)?;
assert!(gridcraft_dax::print_query(&query).starts_with("DEFINE\n MEASURE Sales[Margin] ="));
Ok(())
}
```
## Public API
| Item | Meaning |
| --- | --- |
| `parse_expression(&str) -> Result<Expr, ParseError>` | Parse one expression. One leading `=` (as typed in some editors) is accepted and ignored. |
| `print_expression(&Expr) -> String` | Canonical text. |
| `parse_query(&str) -> Result<Query, ParseError>` | Parse a query: optional `DEFINE`, then one or more `EVALUATE` statements. `EVALUATE <expr>` alone keeps working. |
| `print_query(&Query) -> String` | Canonical multi-line query text. |
| `tokenize(&str) -> Result<Vec<Token>, LexError>` | Tokens with byte spans, including `Eof`. |
| `ParseError { message, span }` / `LexError { message, span }` | `Display + std::error::Error`; the lexer error converts with `From`. |
| `ast::{Expr, ExprKind, Literal, DateTimeLiteral, Name, NameRef, NameStyle, Call, UnaryOp, BinaryOp, Span}` | Expression syntax tree. |
| `ast::{Query, Define, Definition, MeasureDef, ColumnDef, TableDef, VarDef, FunctionDef, MParameterDef}` | Query/`DEFINE` tree. |
| `ast::{Evaluate, OrderItem, StartValue, SortDirection}` | `EVALUATE`, `ORDER BY` and `START AT`. |
| `ast::{FunctionParam, ParameterType, ParameterSubtype, PassingMode}` | `FUNCTION` parameters and annotations. |
| `ast::{VisualShape, Axis, AxisKind, AxisGroup, AxisOrderItem}` | `WITH VISUAL SHAPE`, `AXIS`, `GROUP`, `TOTAL`. |
| `functions::{catalog, lookup}` | Every catalogued function, looked up case-insensitively. |
| `functions::{FunctionSpec, FunctionCategory, ParamKind, ReturnType, BlankPolicy, FunctionFlags, Parameter, Overload}` | Catalog record types. |
| `validate_call(&Call) -> Vec<ValidationError>` | Arity/kind checks for one call; empty for valid or unknown functions. |
| `validate_expression(&Expr) -> Vec<ValidationError>` | Walks the tree and reports every invalid known-function call with its span. |
| `types::{DataType, PseudoType, InferredType, TypeMetadata, TypeError}` | The eight DAX types, the BLANK/Table pseudo-types, inference results and static type errors. |
| `types::{literal_type, infer_type, unary_type, binary_type, arithmetic_type, comparison_coercion, comparison_compatible, comparison_type}` | Literal classification, static inference and the documented operator/coercion tables. |
| `model::{DataModel, ModelTable, ModelColumn, Measure, Relationship, parse_measure}` | Metadata + inline-row model, formula parsing and name validation. |
| `binder::{Binder, BoundExpr, BoundMeasure, bind_formula}` | Name/measure/column resolution, dependency graph and cycle rejection. |
| `eval::{Evaluator, FilterContext}` | Expression/measure evaluator over `DataModel`; a catalogued function whose family is not linked reports "not implemented". |
| `pivot::{pivot, pivot_cross, pivot_fields}` | Row/column grouping helpers. |
| `pivot_table::PivotTable` | Power Pivot-style row/column/filter/value layout with subtotals and grand totals. |
| `storage::{ModelStorage, TableStorage, ColumnStorage, ColumnData}` | Columnar, dictionary-encoded model store with filter/aggregate/relationship indexes. |
| `MAX_INPUT_LEN` (8192 bytes, expressions) / `MAX_QUERY_LEN` (1 MiB, queries) / `MAX_DEPTH` (256) | Limits enforced with errors. |
### Syntax tree
```text
Expr { kind: ExprKind, span: Span }
ExprKind =
Literal(Literal) Integer(i64) | Decimal(f64)
| DateTime(DateTimeLiteral)
| String(String) | Boolean(bool)
| Name(NameRef) table: Option<Name>, name: Name
| Call(Call) name: Name, args: Vec<Expr>
| Unary { op, expr } op: UnaryOp (Plus | Neg | Not)
| Binary { op, left, right } op: BinaryOp
| Table(Vec<Expr>) { value, ... }
| Tuple(Vec<Expr>) (value, ...)
| VarReturn { vars, body } VAR a = 1 ... RETURN body
Query { define: Option<Define>, evaluates: Vec<Evaluate> }
Define { items: Vec<Definition> }
Definition =
Measure(MeasureDef) name: NameRef, expr: Expr
| Column(ColumnDef) name: NameRef, expr: Expr
| Table(TableDef) name: Name, expr: Expr, visual_shape: Option<VisualShape>
| Var(VarDef) name: Name, expr: Expr
| Function(FunctionDef) name: Name, params: Vec<FunctionParam>, body: Expr
| MParameter(MParameterDef) name: Name, expr: Expr
Evaluate { table: Expr, order_by: Vec<OrderItem>, start_at: Vec<StartValue> }
OrderItem { expr: Expr, direction: SortDirection }
StartValue = Literal(Literal) | Parameter(Name) -- @name
FunctionParam { name, ty, subtype, passing, default }
VisualShape { axes: Vec<Axis>, densify: Option<String> }
Axis { kind: AxisKind (Rows | Columns), groups: Vec<AxisGroup>, order_by: Vec<AxisOrderItem> }
AxisGroup { columns: Vec<NameRef>, total: NameRef }
AxisOrderItem { column: NameRef, direction: SortDirection }
```
`Span` is a half-open byte range into the source. `Expr::walk` visits nodes depth-first with an
explicit stack. `Expr` equality compares `ExprKind` only: spans are ignored, so
`parse(print(e)) == e` for every expression the parser produces.
`Name` keeps the source spelling and quoting style (`Bare`, `Quoted`, `Bracketed`); the printer
reproduces that style. A `NameRef` is a table-qualified reference (`'Sales'[Amount]`) or an
unqualified name (`[Amount]`, `Total`, `'Sales'`). `Call` also keeps the spelling (`Sum` stays
`Sum`).
Parentheses are grouping, not AST nodes. A parenthesised comma list is a `Tuple`; inside
`{ ... }` those tuples are the rows of a `Table`.
## Grammar
```text
expression := prefix (binary_operator prefix)* -- precedence-climbing, see the table
prefix := "+" prefix | "-" prefix | NOT prefix | primary
primary := INTEGER | DECIMAL | STRING | TRUE | FALSE
| dt STRING -- validated date/time literal
| name
| name "(" [ expression ("," expression)* ] ")"
| table-qualified-name
| "(" expression ")"
| "(" expression "," expression ("," expression)* ")"
| "{" [ expression ("," expression)* ] "}"
| VAR var_name "=" expression { VAR var_name "=" expression } RETURN expression
name := IDENT | "[" column "]" | "'" table "'"
qualified := (IDENT | "'" table "'") "[" column "]"
query := [ define ] evaluate { evaluate } [ ";" ]
define := DEFINE definition { definition }
definition := MEASURE table '[' name ']' "=" expression
| COLUMN table '[' name ']' "=" expression
| TABLE table_name "=" expression [ visual_shape ]
| VAR var_name "=" expression
| FUNCTION function_name "=" "(" [ param { "," param } ] ")" "=>" expression
| MPARAMETER mparameter_name "=" expression
param := param_name [ ":" [ type ] [ subtype ] [ passing_mode ] ] [ "=" expression ]
evaluate := EVALUATE expression [ order_by ] [ start_at ]
order_by := ORDER BY order_item { "," order_item }
order_item := expression [ ASC | DESC ]
start_at := START AT start_value { "," start_value }
start_value := literal | [ "+" | "-" ] number | "@" name
visual_shape := WITH VISUAL SHAPE axis { axis } [ DENSIFY STRING ]
axis := AXIS ( ROWS | COLUMNS )
group { group }
ORDER BY column_ref [ ASC | DESC ] { "," column_ref [ ASC | DESC ] }
group := GROUP column_ref { "," column_ref } TOTAL column_ref
column_ref := "[" name "]" | table "[" name "]"
```
Statement keywords are matched case-insensitively. There are no statement terminators in the
documented grammar: `MEASURE`, `COLUMN`, `TABLE`, `VAR`, `FUNCTION`, `MPARAMETER` and the
`EVALUATE` token bound definition bodies and separate statements, so no newline is needed.
One or more trailing `;` are accepted as a recovery extension. The `DEFINE` block is optional but
requires at least one entry and must be followed by at least one `EVALUATE`. Duplicate definition
names and forward/backward references are accepted; resolution is a semantic concern.
The shape above is illustrative: the Pratt parser applies the precedence and associativity
table below rather than a fixed grammar cascade.
`*` is not a wildcard token: it is only the multiplication operator.
### Statements
- `EVALUATE` takes any table expression. `ORDER BY` sorts the result and defaults to `ASC`;
`START AT` requires `ORDER BY`, takes literals or `@parameter` references, and may not have
more values than `ORDER BY` items.
- `DEFINE MEASURE`/`COLUMN` names are `<table>[<name>]`; `TABLE`, `FUNCTION` and `MPARAMETER`
names are bare or single-quoted. `VAR` names are bare only. A query-scoped `VAR` has no
`RETURN`; an expression-level `VAR ... RETURN ...` requires one. `RETURN` without a preceding
`VAR` is an error.
- `FUNCTION` parameters may declare a type (`ANYVAL`, `SCALAR`, `TABLE`, `ANYREF`,
`CALENDARREF`, `COLUMNREF`, `MEASUREREF`, `TABLEREF`), a scalar subtype (`BOOLEAN`,
`DATETIME`, `DECIMAL`, `DOUBLE`, `INT64`, `NUMERIC`, `STRING`, `VARIANT`), a passing mode
(`VAL`/`EXPR`) and a default expression. Only `SCALAR` (or an omitted type) accepts a subtype.
- `WITH VISUAL SHAPE` is valid only as the suffix of a `DEFINE TABLE`. It needs one or two axes
(`AXIS ROWS`, `AXIS COLUMNS`, no duplicates), each with at least one `GROUP ... TOTAL` level
and an `ORDER BY` list. `DENSIFY "column"` is optional and last, and takes a double-quoted
string, not a bracketed reference. `AXIS ROWPAGES` is not part of the grammar.
- `MPARAMETER` is the Power BI dynamic M-parameter binding and is accepted as a `DEFINE` entry
even though Microsoft's `DEFINE` grammar omits it.
### Case and escapes
- Keywords (`NOT`, `IN`, `EVALUATE`, `TRUE`, `FALSE`, and every statement keyword) are
case-insensitive. `TRUE`/`FALSE` are literals unless followed by `(` (then they are calls to a
function of that name). The printer writes statement keywords uppercase and keeps identifier
spelling.
- Bare identifiers keep their spelling. Function names may contain `.` (`STDEV.P`).
- Single-quoted table identifiers double an embedded quote: `'It''s'`.
- Bracketed columns double an embedded `]`: `[A]]B]`.
- String literals double an embedded quote: `"a""b"`.
- Number literals are typed: a digit-only literal is an `Integer` (`42`, parsed as `i64`), while
a decimal point or exponent is a `Decimal` (`3.14`, `.5`, `1.`, `1e3`, `1.5E-3`, parsed as
`f64`). The sign is the unary operator, never part of the token. Values must be finite; an
integer that does not fit `i64`, or a decimal that overflows `f64`, is a lexer error with a
span. `Decimal` printing always keeps a decimal point or exponent (`1000.0`, `1e-6`) so the
text re-lexes as a `Decimal`.
- Date/time literals are `dt"YYYY-MM-DD"`, `dt"YYYY-MM-DDThh:mm:ss"` and
`dt"YYYY-MM-DD hh:mm:ss"`. The `dt` prefix is matched case-insensitively but must be adjacent
to the quote; the printer emits lowercase `dt` and padded components. Unpadded month/day/time
components are accepted (`dt"2015-1-9T2:3:0"`). Timezone offsets, fractional seconds,
time-only forms, wrong-case `t`, and invalid calendar dates (including non-leap `1900-02-29`)
are lexer errors.
- `BLANK` is an ordinary identifier. `BLANK()` is a zero-argument call; there is no BLANK literal.
- Comments: `// line`, `-- line`, and `/* block */` (blocks do not nest).
## Operators
Precedence from the operator table (tighter first); operators of equal precedence evaluate left to
right, including `^`:
| Level | Operators | Associativity |
| --- | --- | --- |
| 1 | grouping `()`, function calls | — |
| 2 | `^` | left |
| 3 | unary `+`, `-` | prefix |
| 4 | `*`, `/` | left |
| 5 | binary `+`, `-` | left |
| 6 | `&` | left |
| 7 | `=`, `==`, `<>`, `<`, `>`, `<=`, `>=`, `IN` | left |
| 8 | `NOT` | prefix |
| 9 | `&&` | left |
| 10 | `\|\|` | left |
`=` coerces types at evaluation time; `==` is strict equality. This crate only records which
operator was written. `IN` is a comparison at the same level as `=`, so `1 + 2 IN { 3 }` parses as
`(1 + 2) IN { 3 }`, and it takes a list (`expr IN { v1, v2 }`) or a table expression
(`expr IN VALUES(T[Col])`).
Microsoft's operator reference states that operators of equal precedence are ordered from left to
right, and `^` shares no tier with another operator, so a chain groups left: `2^3^2` is `(2^3)^2` =
64, the value Excel and Power Pivot produce as well. Unary minus binds looser than `^`: `-2^2` parses
as `-(2^2)`.
## Data types and static inference
`types::DataType` is exactly the eight dax.guide types: `Binary`, `Boolean`, `Currency`,
`DateTime`, `Decimal`, `Integer`, `String`, `Variant`. `PseudoType` adds the two Microsoft DAX
types that are not in that list, `Blank` and `Table`; they are inference results, not
`DataType` variants. Each type (including the pseudo-types) has a `TypeMetadata` row with its
internal representation, literal syntax (or `None`), range, precision and notes. Literal
availability is `Boolean`, `DateTime`, `Decimal`, `Integer`, `String`; `Binary`, `Currency` and
`Variant` have no literal, and neither does BLANK (`BLANK()` is a function).
`literal_type(&Literal)` maps a literal to its `DataType`. `infer_type(&Expr) ->
Result<InferredType, TypeError>` infers literals, unary `+`/`-`/`NOT`, binary operators,
`TRUE()`/`FALSE()`/`BLANK()` calls, table constructors, and every catalogued function's documented
`ReturnType` (`Table` for table functions, `Blank` for BLANK, `Unknown` for `Any`/unknown names).
Name references still return `InferredType::Unknown` because they need the model. `Unknown` is not
a DAX type; it is the absence of static information.
The arithmetic and comparison result tables are transcribed from the published DAX operator
reference for `Integer`, `Currency`, `Decimal` ("Real") and `DateTime`:
`arithmetic_type` implements `+`, `-`, `*`, `/` and `^` (a double). The quirks are preserved
rather than normalised: `Integer * DateTime -> Integer`, `Currency * Currency -> Decimal`,
`DateTime - DateTime -> DateTime`, and a `DateTime` on the left of `*` has no published row and is
a `TypeError`. `&` yields `String`; `&&`, `||`, comparisons and `IN` yield `Boolean`; unary `+`
and `-` preserve the numeric type. `Variant` propagates, and BLANK stays polymorphic (for example
`BLANK() + 5` is `Integer` while `BLANK() * 5` is `Blank`).
`comparison_coercion` models `=`, `<>` and ordering: BLANK is coerced to `0`, `""` or `FALSE` for
the other operand's type, and String/Boolean compared with a numeric type is a `TypeError` (the
engine errors; dax.guide also documents a conflicting type rank). `comparison_compatible` and
`comparison_type` also cover `==`, which is strict and does not coerce BLANK. Excel's embedded
engine rejects `==` altogether, but dax.guide documents it and this crate parses it.
This is static typing only. Text-to-number/date/Boolean parsing, BLANK substitution and truth
tables, `5/BLANK()` (Infinity), `0/BLANK()` (NaN), Currency rounding, runtime integer overflow,
IEEE equality and string collation belong to the evaluator. The module documentation lists the
documented conflicts (Currency/Integer endpoints, the DateTime minimum, mixed-type comparisons,
and `dt` literal engine support) instead of hiding them behind one total order.
## Limits, errors and printing
Expressions are capped at 8192 bytes, queries at 1 MiB, and expression nesting at 256 levels; each
limit produces an error, never a stack overflow. The printer and `Expr::walk` use explicit stacks, and
the parser's binary loop is iterative, so a left-associated chain does not recurse — but the chain
still grows the tree one level per operator, and the depth check applies to it: a flat
`1 + 1 + ... + 1` with more than about 256 terms is rejected as too deeply nested (asserted for a
1,000-term chain in `src/tests.rs`). Long generated `&&`, `||` or `&` chains hit the same limit.
Numeric literal overflow (an integer outside `i64`, or a decimal outside finite `f64`) and invalid
date/time literals are lexer errors with the literal's span. Errors carry `message` and a byte
`span`; `Display` includes both. The canonical printer uses
spaces around binary operators, `, ` between arguments/items, and adds parentheses only where
precedence or associativity requires them. Re-parsing canonical text yields the same AST.
`print_query` prints `DEFINE` entries indented one level, each following `EVALUATE` on its own
line with indented `ORDER BY`/`START AT` clauses, and visual-shape axes, groups and `DENSIFY`
indented under their `TABLE`. The simple `EVALUATE <expression>` form stays on one line, so
`print_query(parse_query("EVALUATE 1 + 2"))` is still `EVALUATE 1 + 2`. An expression-level
`VAR ... RETURN ...` prints on one line and is parenthesised when it is an operand, because it
binds looser than every operator. All printing remains iterative.
## Function catalog
`functions::catalog()` returns every function of every
[dax.guide function category](https://dax.guide/functions/), in category order. Each
`FunctionSpec` records the exact arity, parameter kinds, overloads (including variadic
functions), return type, iterator/volatile/not-recommended/Excel flags, description and
parseable examples. Each record carries its descriptive signature (`params`, with `optional`
markers), exact `overloads` (fixed or variadic), `return_type`, `flags` (`iterator`, `volatile`,
`not_recommended`, `excel_compatible`, `direct_query_limited`), `sugar_of`, `blank_policy`,
`description` and `examples`. Every example in the catalog parses with `parse_expression`.
Descriptions and examples are original summaries written for GridCraft. Microsoft's DAX function
documentation is a behavioural reference only: no sentence, definition or sample argument list is
copied from it (or from dax.guide, which republishes Microsoft's wording). Write what the function
returns, what its arguments mean and which edge case it handles, in the project's own voice.
| Category | Functions |
| --- | ---: |
| Aggregation | 22 |
| Date and Time | 24 |
| Filter | 29 |
| Financial | 51 |
| Information | 114 |
| Logical | 13 |
| Math and Trig | 49 |
| Other | 16 |
| Parent-child | 5 |
| Relationship management | 4 |
| Statistical | 43 |
| Table manipulation | 35 |
| Text | 23 |
| Time Intelligence | 45 |
| Visual calculations | 11 |
| **Total** | **484** |
| Function | Arity | Iterator | Sugar of | Blank | Excel | Notes |
| --- | --- | --- | --- | --- | --- | --- |
| `APPROXIMATEDISTINCTCOUNT` | 1 | no | — | BLANK | no | HyperLogLog / DirectQuery pushdown; column reference only. |
| `AVERAGE` | 1 | no | `AVERAGEX` | unspecified | yes | Ignores blanks, includes zero; sources disagree on the empty/all-blank result. |
| `AVERAGEA` | 1 | no | — | unspecified | yes | Booleans are 1/0, any text is 0 and a BLANK cell is 0 in the denominator (Microsoft's 22/5 example); dax.guide marks it not recommended. |
| `AVERAGEX` | 2 | yes | — | BLANK | yes | Row context; blanks ignored, zeros included; empty set observed BLANK. |
| `COUNT` | 1 | no | `COUNTX` | BLANK | yes | Counts numbers, dates and strings; empty strings count, booleans do not. |
| `COUNTA` | 1 | no | `COUNTAX` | BLANK | yes | Counts non-blank values including booleans. |
| `COUNTAX` | 2 | yes | — | BLANK | yes | Row context; booleans count. |
| `COUNTBLANK` | 1 | no | — | unspecified | yes | Empty string counts as blank; dax.guide says never 0, Microsoft Learn says 0 when rows exist. |
| `COUNTROWS` | 0–1 | no | — | BLANK | yes\* | \*The zero-argument form is rejected by Excel's embedded engine; pass a table there. |
| `COUNTX` | 2 | yes | — | BLANK | yes | Row context; booleans are not counted. |
| `DISTINCTCOUNT` | 1 | no | — | BLANK | yes | BLANK is one distinct value; totals are non-additive. |
| `DISTINCTCOUNTNOBLANK` | 1 | no | `DISTINCTCOUNT` | unspecified | no | Excludes BLANK; rejected by Excel's embedded engine. |
| `MAX` | 1–2 | no | `MAXX`\* | unspecified | yes | \*Only the one-argument column overload is sugar. Two scalars treat BLANK as significant per dax.guide, as 0 per Microsoft Learn. |
| `MAXA` | 1 | no | — | unspecified | yes | TRUE/FALSE become 1/0; empty result conflicts across sources. |
| `MAXX` | 2–3 | yes | — | unspecified | yes | Optional third `Variant` compares mixed types per `ORDER BY DESC`. |
| `MIN` | 1–2 | no | `MINX`\* | unspecified | yes | \*Only the one-argument column overload is sugar. Two scalars have the same BLANK conflict as `MAX`. |
| `MINA` | 1 | no | — | unspecified | yes | TRUE/FALSE become 1/0; empty result conflicts across sources. |
| `MINX` | 2–3 | yes | — | unspecified | yes | Optional third `Variant` compares mixed types per `ORDER BY ASC`. |
| `PRODUCT` | 1 | no | `PRODUCTX` | BLANK | yes | Multiplies numeric cells, ignoring blanks, logical values and text. |
| `PRODUCTX` | 2 | yes | — | BLANK | yes | Row context; ignores blank results, unlike the `*` operator. |
| `SUM` | 1 | no | `SUMX` | BLANK | yes | Adds numeric cells, ignoring blanks, logical values and text. |
| `SUMX` | 2 | yes | — | BLANK | yes | Row context; blanks, logical values and text ignored. |
`AVERAGEA`, `MAXA` and `MINA` use the X function internally but are not pure sugar: their
boolean/text coercions differ, so `sugar_of` is `None`. `direct_query_limited` is `true` for all
22 functions because Microsoft Learn excludes them from calculated columns and RLS rules in
DirectQuery mode; `APPROXIMATEDISTINCTCOUNT` still supports DirectQuery pushdown in measures.
### Blank policies
- `BlankWhenEmpty` — the result is BLANK when there are no rows or no qualifying value. Used
where dax.guide and the observed engine agree, including the observed empty-set results of
`SUMX`, `AVERAGEX`, `COUNTX` and `PRODUCTX`.
- `Unspecified` — dax.guide and Microsoft Learn disagree, or the sources are silent. This is
deliberate: the catalog does not pick a winner for `AVERAGE`/`AVERAGEA`, `COUNTBLANK`,
`MAX`/`MIN`/`MAXA`/`MINA` or `MAXX`/`MINX`.
- `ZeroWhenRowsButNoMatch` — documents the Microsoft Learn rule. No function uses it today
because no engine observation supported it; it stays in the enum for a future evaluator that
needs to model the conflicting rule explicitly.
### Static validation
`validate_expression` walks the AST and reports every argument-count or argument-kind error for a
catalogued function. Spans point at the offending argument for kind errors and at the whole call
for arity errors; unknown functions are ignored but their arguments are still visited.
A `ParamKind::Column` argument must be a bracketed `NameRef` (`Sales[Amount]` or `[Amount]`), so
`SUM ( 1 )` and `AVERAGE ( 1 + 1 )` are rejected. A `ParamKind::Table` argument is rejected when
it is certainly not a table — a literal, an operator expression or a bracketed column reference —
so `COUNTROWS ( 1 )` and `COUNTROWS ( Sales[Amount] )` fail while
`COUNTROWS ( DISTINCT ( Sales[Region] ) )`, table variables and `{ 1, 2 }` are accepted.
`COUNTROWS ()` is valid in the catalog (the Excel limitation is recorded on the function, not
enforced here). `Date`, `Text`, `Number`, `Boolean`, `Function`, `Reference`, `Json`, `Variant`,
`Expression`, `Scalar`, `Logical` and `Any` are not statically decidable: DAX's implicit
coercions need the model, so they are recorded for documentation and future type checking only.
Variadic overloads repeat their last parameter kind for every additional argument; the third
`Variant` argument of `MAXX`/`MINX` accepts any expression.
## Model, binder and evaluator
`model::DataModel` is the metadata + inline-row view used by the binder and evaluator. JSON shape:
```json
{
"tables": [{"name": "Sales", "columns": [{"name": "Region"}, {"name": "Amount"}],
"rows": [["East", 10], ["West", 20]]}],
"relationships": [],
"measures": [{"name": "Total Sales", "formula": "SUM(Sales[Amount])", "table": "Sales"}]
}
```
`DataModel::parse_formulas` parses each measure and validates table/column/relationship names.
`Binder::bind_expression` resolves `Table[Column]`, measures, variables and function calls;
`Binder::bind_measure` and `Binder::dependency_graph` expose direct measure dependencies and reject
cycles. `Evaluator::new` pre-binds the measures and evaluates scalar or table expressions with a
`FilterContext`; `pivot::pivot` groups a measure by row fields.
The evaluator's core switch implements the scalar spine — literals, operators, `VAR`/`RETURN`,
context transition, `CALCULATE`/`FILTER`/`ALL`/`VALUES`/`DISTINCT`/`SELECTEDVALUE`, the
aggregations and their `*X` iterators, and the logical functions that need lazy arguments — over
a columnar store (`storage`: typed columns, dictionary strings, null bitmaps, relationship
indexes). `Evaluator::new` materializes the store once and uses it for filters, aggregates,
`VALUES`/`DISTINCT`, `COUNTROWS` and `RELATED*` when `ModelStorage::is_faithful` holds; other
models keep the row scan. The remaining catalogued functions arrive in family modules under
`src/eval/`, one module per family, each registering itself through the evaluator's dispatch
array; a family that is not linked reports the catalogued call as not implemented.
## Extending in later PRs
- Statement semantics (name resolution, duplicate-name shadowing, `START AT` value types,
function overloading and recursion rules, visual-shape evaluation) are not checked here; the
parser accepts what the grammar accepts. Query-defined tables/columns and `MPARAMETER` are
engine-specific, and the crate records them without validating a model.
- `Call`, `NameRef` and `NameStyle` keep spelling/quoting so catalog and type work can resolve
names without re-lexing.
- `types::infer_type` resolves every catalogued call through its documented `ReturnType`, plus
literals, operators, `TRUE()`/`FALSE()`/`BLANK()` and `VAR`/`RETURN` blocks. `InferredType::Unknown`
remains for names and functions whose return type is `Any`/unknown.
- The binder resolves tables, columns, measures, variables and documented keyword parameters.
Each evaluator family ships with its own integration suite under `tests/eval_*.rs`.
## Example
```sh
cargo run -p gridcraft-dax --example parse -- "1 + 2 * 3"
cargo run -p gridcraft-dax --example parse -- "EVALUATE SUM('Sales'[Amount])"
cargo run -p gridcraft-dax --example parse -- "DEFINE MEASURE Sales[M] = SUM(Sales[Amount]) EVALUATE Sales ORDER BY [M] DESC"
echo 'NOT TRUE || FALSE && TRUE' | cargo run -p gridcraft-dax --example parse
```
+69
View File
@@ -0,0 +1,69 @@
//! Parse DAX from the command line (or stdin), print its syntax tree and canonical text.
//!
//! ```text
//! cargo run -p gridcraft-dax --example parse -- "1 + 2 * 3"
//! echo "EVALUATE SUM('Sales'[Amount])" | cargo run -p gridcraft-dax --example parse
//! ```
use std::io::{self, Read};
use gridcraft_dax::{TokenKind, parse_expression, parse_query, print_expression, print_query, tokenize};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut text = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
if text.trim().is_empty() {
io::stdin().read_to_string(&mut text)?;
}
let text = text.trim();
if text.is_empty() {
return Err("no DAX expression supplied; pass it as an argument or on stdin".into());
}
print!("{}", render(text)?);
Ok(())
}
/// Parses and renders one input. Queries are preferred; when the query parser fails, a valid
/// expression is still accepted (`DEFINE` is a legal bare name), and the query diagnostic is kept
/// only when both parsers fail for input that starts with a query keyword.
fn render(text: &str) -> Result<String, String> {
match parse_query(text) {
Ok(query) => Ok(format!("Query\n{query:#?}\nCanonical: {}\n", print_query(&query))),
Err(query_error) => {
let expr = match parse_expression(text) {
Ok(expr) => expr,
Err(expr_error) => {
if starts_with_query_keyword(text) {
return Err(query_error.to_string());
}
return Err(expr_error.to_string());
}
};
Ok(format!("AST\n{expr:#?}\nCanonical: {}\n", print_expression(&expr)))
}
}
}
fn starts_with_query_keyword(text: &str) -> bool {
tokenize(text).is_ok_and(|tokens| match tokens.first().map(|token| &token.kind) {
Some(TokenKind::Evaluate) => true,
Some(TokenKind::Ident(word)) => word.eq_ignore_ascii_case("DEFINE"),
_ => false,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn query_only_keywords_stay_on_the_query_parser() {
assert!(starts_with_query_keyword("EVALUATE Sales"));
assert!(starts_with_query_keyword("DEFINE MEASURE Sales[M] = 1 EVALUATE Sales"));
assert!(starts_with_query_keyword(" define measure Sales[M] = 1"));
assert!(!starts_with_query_keyword("SUM(Sales[Amount])"));
// `DEFINE` alone is a valid expression, so the expression parser wins.
assert!(render("DEFINE").expect("bare name expression").starts_with("AST"));
let error = render("DEFINE MEASURE").expect_err("malformed query");
assert!(error.contains("measure name"), "{error}");
}
}
+653
View File
@@ -0,0 +1,653 @@
//! DAX syntax tree.
//!
//! Every expression node carries a [`Span`] in byte offsets into the source text. Statement
//! nodes (`DEFINE` entries, `EVALUATE`, `ORDER BY`, visual shapes) group expressions and names.
//! [`Expr`] equality deliberately ignores spans (`PartialEq` compares [`ExprKind`] only), which
//! makes the parser/printer round-trip invariant expressible as `parse(print(e)) == e`.
/// A half-open byte range `start..end` into the source text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Span {
pub start: usize,
pub end: usize,
}
impl Span {
pub const fn new(start: usize, end: usize) -> Self {
Span { start, end }
}
/// An empty span at byte offset 0.
pub const fn empty() -> Self {
Span { start: 0, end: 0 }
}
pub const fn len(self) -> usize {
self.end.saturating_sub(self.start)
}
pub const fn is_empty(self) -> bool {
self.start >= self.end
}
/// The smallest span covering both operands.
pub fn to(self, other: Span) -> Span {
Span { start: self.start.min(other.start), end: self.end.max(other.end) }
}
}
/// A `dt"..."` date/time literal.
///
/// Components are validated when the literal is lexed. The `has_time` flag distinguishes
/// `dt"2023-05-19"` from `dt"2023-05-19T00:00:00"`, which are different literal forms even
/// though they denote the same serial value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DateTimeLiteral {
pub year: u32,
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
pub second: u32,
pub has_time: bool,
}
impl DateTimeLiteral {
/// Canonical `YYYY-MM-DD` / `YYYY-MM-DDThh:mm:ss` text, without the `dt` prefix or quotes.
pub fn canonical(self) -> String {
format!("{self}")
}
}
impl std::fmt::Display for DateTimeLiteral {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)?;
if self.has_time {
write!(f, "T{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?;
}
Ok(())
}
}
/// A DAX literal value.
///
/// Integer and Decimal are distinct literal kinds (not one numeric kind): `42` is an
/// [`Literal::Integer`] and `42.0`, `42e0` are [`Literal::Decimal`] values. The sign of a
/// negative number is the unary `-` operator, never part of the literal.
#[derive(Clone, Debug, PartialEq)]
pub enum Literal {
/// A 64-bit signed integer literal such as `42`.
Integer(i64),
/// An IEEE-754 double literal written with a decimal point or exponent: `3.14`, `.5`, `1e3`.
Decimal(f64),
/// A `dt"..."` literal.
DateTime(DateTimeLiteral),
String(String),
Boolean(bool),
}
/// How an identifier was written, so the printer can reproduce it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NameStyle {
/// `Sales`
Bare,
/// `'Sales Table'`
Quoted,
/// `[Amount]`
Bracketed,
}
/// A single identifier, preserving its source spelling and quoting style.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Name {
/// Text with quoting removed and doubled quote/bracket escapes resolved.
pub text: String,
pub style: NameStyle,
}
impl Name {
pub fn bare(text: impl Into<String>) -> Self {
Name { text: text.into(), style: NameStyle::Bare }
}
pub fn quoted(text: impl Into<String>) -> Self {
Name { text: text.into(), style: NameStyle::Quoted }
}
pub fn bracketed(text: impl Into<String>) -> Self {
Name { text: text.into(), style: NameStyle::Bracketed }
}
}
/// A name, optionally table-qualified: `'Sales'[Amount]`, `Sales[Amount]` or `[Amount]`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct NameRef {
/// Table part of a column/measure reference.
pub table: Option<Name>,
pub name: Name,
}
impl NameRef {
pub fn unqualified(name: Name) -> Self {
NameRef { table: None, name }
}
pub fn qualified(table: Name, name: Name) -> Self {
NameRef { table: Some(table), name }
}
}
/// A function call. The name keeps the spelling used in the source (`Sum`, `SUM`).
#[derive(Clone, Debug, PartialEq)]
pub struct Call {
pub name: Name,
pub args: Vec<Expr>,
}
/// Prefix operators. `Not` is the keyword operator, not a function call.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum UnaryOp {
Plus,
Neg,
Not,
}
impl UnaryOp {
/// Binding power, higher binds tighter (DAX precedence levels 3 and 8).
pub const fn precedence(self) -> u8 {
match self {
UnaryOp::Plus | UnaryOp::Neg => 80,
UnaryOp::Not => 30,
}
}
pub const fn symbol(self) -> &'static str {
match self {
UnaryOp::Plus => "+",
UnaryOp::Neg => "-",
UnaryOp::Not => "NOT",
}
}
}
/// Binary operators, in the precedence order of <https://dax.guide/operators/>.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Pow,
Concat,
Eq,
StrictEq,
Ne,
Lt,
Gt,
Le,
Ge,
And,
Or,
In,
}
impl BinaryOp {
pub const fn symbol(self) -> &'static str {
match self {
BinaryOp::Add => "+",
BinaryOp::Sub => "-",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
BinaryOp::Pow => "^",
BinaryOp::Concat => "&",
BinaryOp::Eq => "=",
BinaryOp::StrictEq => "==",
BinaryOp::Ne => "<>",
BinaryOp::Lt => "<",
BinaryOp::Gt => ">",
BinaryOp::Le => "<=",
BinaryOp::Ge => ">=",
BinaryOp::And => "&&",
BinaryOp::Or => "||",
BinaryOp::In => "IN",
}
}
/// Binding power, higher binds tighter. The values encode the ten precedence levels
/// from the operator table: parentheses/calls, `^`, unary sign, `* /`, `+ -`, `&`,
/// comparisons (including `IN`), `NOT`, `&&`, `||`.
pub const fn precedence(self) -> u8 {
match self {
BinaryOp::Pow => 90,
BinaryOp::Mul | BinaryOp::Div => 70,
BinaryOp::Add | BinaryOp::Sub => 60,
BinaryOp::Concat => 50,
// `IN` is a comparison, at the same tier as `=`/`<` (Microsoft's operator table).
BinaryOp::In | BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => 40,
BinaryOp::And => 20,
BinaryOp::Or => 10,
}
}
/// DAX binary operators all associate to the left. Microsoft's operator reference puts `^` in
/// its own precedence tier and states that operators of equal precedence are ordered from left
/// to right, so `2^3^2` is `(2^3)^2` = 64 — the same value Excel and Power Pivot produce.
pub const fn is_left_associative(self) -> bool {
true
}
pub const fn is_right_associative(self) -> bool {
false
}
pub const fn is_comparison(self) -> bool {
matches!(self, BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge)
}
pub const fn is_logical(self) -> bool {
matches!(self, BinaryOp::And | BinaryOp::Or)
}
}
/// The shape of an expression, without its span.
#[derive(Clone, Debug, PartialEq)]
pub enum ExprKind {
Literal(Literal),
/// A bare, quoted or table-qualified name.
Name(NameRef),
/// `SUM(1, 2)`.
Call(Call),
Unary {
op: UnaryOp,
expr: Box<Expr>,
},
Binary {
op: BinaryOp,
left: Box<Expr>,
right: Box<Expr>,
},
/// A table constructor `{ 1, 2 }`. Rows are [`ExprKind::Tuple`] values.
Table(Vec<Expr>),
/// A row constructor / parenthesised comma list `(1, "a")`.
Tuple(Vec<Expr>),
/// An expression-level `VAR <name> = <expr> ... RETURN <expr>` block.
VarReturn {
vars: Vec<VarDecl>,
body: Box<Expr>,
},
}
/// One `VAR <name> = <expression>` declaration inside an [`ExprKind::VarReturn`].
///
/// The name is a plain identifier: DAX variable names cannot be quoted or bracketed. Declarations
/// are sequential, so `nameN` is visible only to `expressionN+1` and to the `RETURN` body.
#[derive(Clone, Debug, PartialEq)]
pub struct VarDecl {
pub name: Name,
pub expr: Expr,
}
/// A DAX expression with its source span.
#[derive(Clone, Debug)]
pub struct Expr {
pub kind: ExprKind,
pub span: Span,
}
impl Expr {
pub fn new(kind: ExprKind, span: Span) -> Self {
Expr { kind, span }
}
pub fn literal(value: Literal, span: Span) -> Self {
Expr::new(ExprKind::Literal(value), span)
}
/// The tree depth (a leaf is 1), computed iteratively so it is safe on any shape the
/// parser accepts. The parser uses this to bound the AST that recursive `Debug`,
/// `PartialEq` and drop glue would otherwise walk.
pub fn depth(&self) -> usize {
let mut max = 0;
let mut stack = vec![(self, 1usize)];
while let Some((node, depth)) = stack.pop() {
max = max.max(depth);
match &node.kind {
ExprKind::Call(call) => stack.extend(call.args.iter().map(|e| (e, depth + 1))),
ExprKind::Unary { expr, .. } => stack.push((expr, depth + 1)),
ExprKind::Binary { left, right, .. } => {
stack.push((right, depth + 1));
stack.push((left, depth + 1));
}
ExprKind::Table(items) | ExprKind::Tuple(items) => {
stack.extend(items.iter().map(|e| (e, depth + 1)));
}
ExprKind::VarReturn { vars, body } => {
stack.push((body, depth + 1));
stack.extend(vars.iter().map(|var| (&var.expr, depth + 1)));
}
ExprKind::Literal(_) | ExprKind::Name(_) => {}
}
}
max
}
/// Visits every node depth-first, parents before children. Iterative, so deeply nested
/// (but within the parser limits) trees cannot overflow the stack.
pub fn walk<'a>(&'a self, f: &mut dyn FnMut(&'a Expr)) {
let mut stack = vec![self];
while let Some(node) = stack.pop() {
f(node);
match &node.kind {
ExprKind::Call(call) => stack.extend(call.args.iter().rev()),
ExprKind::Unary { expr, .. } => stack.push(expr),
ExprKind::Binary { left, right, .. } => {
stack.push(right);
stack.push(left);
}
ExprKind::Table(items) | ExprKind::Tuple(items) => stack.extend(items.iter().rev()),
ExprKind::VarReturn { vars, body } => {
stack.push(body);
stack.extend(vars.iter().rev().map(|var| &var.expr));
}
ExprKind::Literal(_) | ExprKind::Name(_) => {}
}
}
}
}
/// Spans do not participate in equality: reparsing printed text produces the same AST.
impl PartialEq for Expr {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind
}
}
/// A complete DAX query: an optional `DEFINE` block followed by one or more `EVALUATE`
/// statements.
///
/// A query always has at least one [`Evaluate`]; the parser rejects `DEFINE` without a following
/// `EVALUATE`. For the simple form `EVALUATE <expression>` the `define` field is `None` and
/// `evaluates` holds exactly one entry with no clauses.
#[derive(Clone, Debug, PartialEq)]
pub struct Query {
pub define: Option<Define>,
pub evaluates: Vec<Evaluate>,
}
/// The `DEFINE` block of a query. One block applies to every `EVALUATE` statement.
#[derive(Clone, Debug, PartialEq)]
pub struct Define {
pub items: Vec<Definition>,
}
/// One entry of a `DEFINE` block.
#[derive(Clone, Debug, PartialEq)]
pub enum Definition {
Measure(MeasureDef),
Column(ColumnDef),
Table(TableDef),
Var(VarDef),
Function(FunctionDef),
MParameter(MParameterDef),
}
/// `MEASURE <table>[<measure>] = <scalar expression>`.
#[derive(Clone, Debug, PartialEq)]
pub struct MeasureDef {
pub name: NameRef,
pub expr: Expr,
}
/// `COLUMN <table>[<column>] = <scalar expression>`.
#[derive(Clone, Debug, PartialEq)]
pub struct ColumnDef {
pub name: NameRef,
pub expr: Expr,
}
/// `VAR <name> = <expression>` in a `DEFINE` block. Unlike an expression-level
/// [`ExprKind::VarReturn`], a query-scoped variable has no `RETURN`.
#[derive(Clone, Debug, PartialEq)]
pub struct VarDef {
pub name: Name,
pub expr: Expr,
}
/// `TABLE <name> = <table expression> [WITH VISUAL SHAPE ...]`.
#[derive(Clone, Debug, PartialEq)]
pub struct TableDef {
pub name: Name,
pub expr: Expr,
pub visual_shape: Option<VisualShape>,
}
/// `MPARAMETER <name> = <expression>`: a Power BI dynamic M parameter binding.
#[derive(Clone, Debug, PartialEq)]
pub struct MParameterDef {
pub name: Name,
pub expr: Expr,
}
/// A query-defined function: `FUNCTION <name> = (<param>, ...) => <body>`.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionDef {
pub name: Name,
pub params: Vec<FunctionParam>,
pub body: Expr,
}
/// One parameter of a [`FunctionDef`].
///
/// Every annotation is optional: `p`, `p : INT64`, `p : SCALAR INT64 VAL` and `p = 1` are all
/// valid parameter declarations.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionParam {
pub name: Name,
pub ty: Option<ParameterType>,
pub subtype: Option<ParameterSubtype>,
pub passing: Option<PassingMode>,
pub default: Option<Expr>,
}
/// The DAX user-defined-function parameter types.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ParameterType {
AnyVal,
Scalar,
Table,
AnyRef,
CalendarRef,
ColumnRef,
MeasureRef,
TableRef,
}
impl ParameterType {
/// The canonical uppercase keyword.
pub const fn keyword(self) -> &'static str {
match self {
ParameterType::AnyVal => "ANYVAL",
ParameterType::Scalar => "SCALAR",
ParameterType::Table => "TABLE",
ParameterType::AnyRef => "ANYREF",
ParameterType::CalendarRef => "CALENDARREF",
ParameterType::ColumnRef => "COLUMNREF",
ParameterType::MeasureRef => "MEASUREREF",
ParameterType::TableRef => "TABLEREF",
}
}
/// Recognises a type keyword case-insensitively.
pub fn from_keyword(word: &str) -> Option<Self> {
Some(match word.to_ascii_uppercase().as_str() {
"ANYVAL" => ParameterType::AnyVal,
"SCALAR" => ParameterType::Scalar,
"TABLE" => ParameterType::Table,
"ANYREF" => ParameterType::AnyRef,
"CALENDARREF" => ParameterType::CalendarRef,
"COLUMNREF" => ParameterType::ColumnRef,
"MEASUREREF" => ParameterType::MeasureRef,
"TABLEREF" => ParameterType::TableRef,
_ => return None,
})
}
}
/// The scalar subtypes, which are only valid together with [`ParameterType::Scalar`] (or alone,
/// as in the documented `p : INT64` shorthand).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ParameterSubtype {
Boolean,
DateTime,
Decimal,
Double,
Int64,
Numeric,
String,
Variant,
}
impl ParameterSubtype {
pub const fn keyword(self) -> &'static str {
match self {
ParameterSubtype::Boolean => "BOOLEAN",
ParameterSubtype::DateTime => "DATETIME",
ParameterSubtype::Decimal => "DECIMAL",
ParameterSubtype::Double => "DOUBLE",
ParameterSubtype::Int64 => "INT64",
ParameterSubtype::Numeric => "NUMERIC",
ParameterSubtype::String => "STRING",
ParameterSubtype::Variant => "VARIANT",
}
}
pub fn from_keyword(word: &str) -> Option<Self> {
Some(match word.to_ascii_uppercase().as_str() {
"BOOLEAN" => ParameterSubtype::Boolean,
"DATETIME" => ParameterSubtype::DateTime,
"DECIMAL" => ParameterSubtype::Decimal,
"DOUBLE" => ParameterSubtype::Double,
"INT64" => ParameterSubtype::Int64,
"NUMERIC" => ParameterSubtype::Numeric,
"STRING" => ParameterSubtype::String,
"VARIANT" => ParameterSubtype::Variant,
_ => return None,
})
}
}
/// How a function argument is passed: `VAL` (eagerly) or `EXPR` (lazily).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PassingMode {
Val,
Expr,
}
impl PassingMode {
pub const fn keyword(self) -> &'static str {
match self {
PassingMode::Val => "VAL",
PassingMode::Expr => "EXPR",
}
}
pub fn from_keyword(word: &str) -> Option<Self> {
match word.to_ascii_uppercase().as_str() {
"VAL" => Some(PassingMode::Val),
"EXPR" => Some(PassingMode::Expr),
_ => None,
}
}
}
/// One `EVALUATE <table expression> [ORDER BY ...] [START AT ...]` statement.
#[derive(Clone, Debug, PartialEq)]
pub struct Evaluate {
pub table: Expr,
pub order_by: Vec<OrderItem>,
pub start_at: Vec<StartValue>,
}
/// One item of a query-level `ORDER BY` clause.
#[derive(Clone, Debug, PartialEq)]
pub struct OrderItem {
pub expr: Expr,
pub direction: SortDirection,
}
/// The sort direction of an `ORDER BY` item. An omitted direction parses as
/// [`SortDirection::Asc`], and the printer writes the keyword explicitly.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SortDirection {
Asc,
Desc,
}
impl SortDirection {
pub const fn keyword(self) -> &'static str {
match self {
SortDirection::Asc => "ASC",
SortDirection::Desc => "DESC",
}
}
pub const fn is_ascending(self) -> bool {
matches!(self, SortDirection::Asc)
}
}
/// One value of a `START AT` clause: a constant or an XMLA `@parameter` reference.
///
/// Start values are constants, not expressions. A sign in front of a numeric literal is folded
/// into the literal (`START AT -1`); everything else must be a literal or `@name`.
#[derive(Clone, Debug, PartialEq)]
pub enum StartValue {
Literal(Literal),
Parameter(Name),
}
/// The `WITH VISUAL SHAPE` clause of a query-defined table.
#[derive(Clone, Debug, PartialEq)]
pub struct VisualShape {
pub axes: Vec<Axis>,
/// The optional `DENSIFY "<column>"` clause, always last.
pub densify: Option<String>,
}
/// One `AXIS ROWS` / `AXIS COLUMNS` clause of a visual shape.
#[derive(Clone, Debug, PartialEq)]
pub struct Axis {
pub kind: AxisKind,
pub groups: Vec<AxisGroup>,
pub order_by: Vec<AxisOrderItem>,
}
/// The axis of a visual shape. Only these two are documented.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AxisKind {
Rows,
Columns,
}
impl AxisKind {
pub const fn keyword(self) -> &'static str {
match self {
AxisKind::Rows => "ROWS",
AxisKind::Columns => "COLUMNS",
}
}
}
/// One `GROUP <column>, ... TOTAL <column>` level of an axis.
#[derive(Clone, Debug, PartialEq)]
pub struct AxisGroup {
pub columns: Vec<NameRef>,
pub total: NameRef,
}
/// One column of an axis `ORDER BY` clause.
#[derive(Clone, Debug, PartialEq)]
pub struct AxisOrderItem {
pub column: NameRef,
pub direction: SortDirection,
}
+425
View File
@@ -0,0 +1,425 @@
//! Name binding for DAX expressions and measures.
//!
//! The binder resolves table names, `Table[Column]` references, measures and expression-level
//! `VAR` names against a [`DataModel`]. It validates catalogued function calls with the same
//! arity/kind rules as [`crate::validate`], and builds the measure dependency graph.
//!
//! It is deliberately static: row context and filter context are evaluator concerns. A bracketed
//! column that is not qualified by a table is left as [`BoundExpr::UnqualifiedColumn`] so the
//! evaluator can resolve it from the current row context.
use std::collections::{BTreeMap, BTreeSet};
use crate::ast::{BinaryOp, Literal, NameRef, UnaryOp};
use crate::model::DataModel;
use crate::{Call, Expr, ExprKind, FunctionSpec, ParamKind, lookup, parse_expression, validate_call};
/// A name-resolution error with the source span.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("{message} at bytes {}..{}", span.start, span.end)]
pub struct BindError {
pub message: String,
pub span: crate::Span,
}
impl BindError {
fn new(message: impl Into<String>, span: crate::Span) -> Self {
BindError { message: message.into(), span }
}
}
/// The bound form of an expression.
#[derive(Clone, Debug, PartialEq)]
pub enum BoundExpr {
Literal(Literal),
/// A resolved `Table[Column]` reference.
Column {
table: usize,
column: usize,
},
/// `[Column]` without a table qualifier: resolved from the evaluator's row context.
UnqualifiedColumn {
name: String,
},
/// A model measure reference.
Measure(usize),
/// A table reference.
Table(usize),
/// A catalogued function call with bound arguments.
Call {
spec: &'static FunctionSpec,
args: Vec<BoundExpr>,
},
Unary {
op: UnaryOp,
expr: Box<BoundExpr>,
},
Binary {
op: BinaryOp,
left: Box<BoundExpr>,
right: Box<BoundExpr>,
},
/// `{ value, ... }`.
TableConstructor(Vec<BoundExpr>),
/// `( value, ... )`.
Tuple(Vec<BoundExpr>),
/// A variable reference.
///
/// `index` is the variable's absolute slot in the cumulative stack of every enclosing
/// [`BoundExpr::VarReturn`] block — outer blocks first, each block appending its own
/// declarations in order — not its position inside the innermost `vars` list. The evaluator
/// pushes each block's values onto the same stack, so the index stays valid across nesting.
Variable {
index: usize,
name: String,
},
/// A function-specific keyword argument (`DAY` in `DATEDIFF`, a type name in `DATATABLE`).
Keyword(String),
/// `VAR name = expr ... RETURN body`.
VarReturn {
vars: Vec<BoundVariable>,
body: Box<BoundExpr>,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct BoundVariable {
pub name: String,
pub expr: BoundExpr,
}
/// A bound measure with its direct measure dependencies.
#[derive(Clone, Debug, PartialEq)]
pub struct BoundMeasure {
pub name: String,
pub expr: BoundExpr,
pub dependencies: BTreeSet<String>,
}
/// Binds expressions against one model.
pub struct Binder<'a> {
model: &'a DataModel,
}
impl<'a> Binder<'a> {
pub fn new(model: &'a DataModel) -> Self {
Binder { model }
}
pub fn model(&self) -> &'a DataModel {
self.model
}
/// Binds an expression with no variables in scope.
pub fn bind_expression(&self, expr: &Expr) -> Result<BoundExpr, BindError> {
self.bind_with_vars(expr, &mut Vec::new())
}
/// Parses and binds a measure formula. The model's measures must have been prepared with
/// [`DataModel::parse_formulas`].
pub fn bind_measure(&self, name: &str) -> Result<BoundMeasure, BindError> {
let index = self.model.measure_index(name).ok_or_else(|| BindError::new(format!("unknown measure `{name}`"), crate::Span::empty()))?;
let measure = &self.model.measures[index];
if measure.expr.is_none() {
return Err(BindError::new(
format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name),
crate::Span::empty(),
));
}
let Some(formula) = measure.expr.as_ref() else {
return Err(BindError::new(
format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name),
crate::Span::empty(),
));
};
let expr = self.bind_expression(formula)?;
let mut dependencies = BTreeSet::new();
collect_measure_names(self.model, &expr, &mut dependencies);
Ok(BoundMeasure { name: measure.name.clone(), expr, dependencies })
}
/// Builds the direct measure dependency graph and rejects cycles.
pub fn dependency_graph(&self) -> Result<BTreeMap<String, BTreeSet<String>>, BindError> {
let mut graph = BTreeMap::new();
for measure in &self.model.measures {
let bound = self.bind_measure(&measure.name)?;
graph.insert(bound.name, bound.dependencies);
}
let mut state: BTreeMap<String, u8> = BTreeMap::new();
for name in graph.keys() {
self.visit(name, &graph, &mut state)?;
}
Ok(graph)
}
fn visit(&self, name: &str, graph: &BTreeMap<String, BTreeSet<String>>, state: &mut BTreeMap<String, u8>) -> Result<(), BindError> {
// Iterative: a measure chain comes from the model JSON, so its length must not grow the
// call stack (a long chain would otherwise abort the process instead of returning an error).
if state.get(name).copied() == Some(2) {
return Ok(());
}
let empty = BTreeSet::new();
state.insert(name.to_string(), 1);
let mut stack: Vec<(&str, std::collections::btree_set::Iter<'_, String>)> = vec![(name, graph.get(name).unwrap_or(&empty).iter())];
while let Some((current, dependencies)) = stack.last_mut() {
match dependencies.next() {
Some(dependency) => match state.get(dependency.as_str()).copied() {
Some(2) => {}
Some(1) => {
return Err(BindError::new(format!("circular measure dependency involving `{dependency}`"), crate::Span::empty()));
}
_ => {
state.insert(dependency.clone(), 1);
stack.push((dependency.as_str(), graph.get(dependency).unwrap_or(&empty).iter()));
}
},
None => {
state.insert((*current).to_string(), 2);
stack.pop();
}
}
}
Ok(())
}
fn bind_with_vars(&self, expr: &Expr, vars: &mut Vec<String>) -> Result<BoundExpr, BindError> {
match &expr.kind {
ExprKind::Literal(literal) => Ok(BoundExpr::Literal(literal.clone())),
ExprKind::Name(name) => self.bind_name(name, expr.span, vars),
ExprKind::Call(call) => self.bind_call(call, expr.span, vars),
ExprKind::Unary { op, expr: inner } => Ok(BoundExpr::Unary { op: *op, expr: Box::new(self.bind_with_vars(inner, vars)?) }),
ExprKind::Binary { op, left, right } => Ok(BoundExpr::Binary {
op: *op,
left: Box::new(self.bind_with_vars(left, vars)?),
right: Box::new(self.bind_with_vars(right, vars)?),
}),
ExprKind::Table(items) => {
Ok(BoundExpr::TableConstructor(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::<Result<_, _>>()?))
}
ExprKind::Tuple(items) => Ok(BoundExpr::Tuple(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::<Result<_, _>>()?)),
ExprKind::VarReturn { vars: declarations, body } => {
let mut bound = Vec::with_capacity(declarations.len());
let mut names = vars.clone();
for declaration in declarations {
let value = self.bind_with_vars(&declaration.expr, &mut names)?;
names.push(declaration.name.text.clone());
bound.push(BoundVariable { name: declaration.name.text.clone(), expr: value });
}
let body = self.bind_with_vars(body, &mut names)?;
Ok(BoundExpr::VarReturn { vars: bound, body: Box::new(body) })
}
}
}
fn bind_name(&self, name: &NameRef, span: crate::Span, vars: &[String]) -> Result<BoundExpr, BindError> {
if let Some(table) = &name.table {
let table_index = self.model.table_index(&table.text).ok_or_else(|| BindError::new(format!("unknown table `{}`", table.text), span))?;
if let Some(column_index) = self.model.column_index(table_index, &name.name.text) {
return Ok(BoundExpr::Column { table: table_index, column: column_index });
}
// `Sales[Total Sales]` names a measure homed on the qualifying table; DAX allows the
// table qualifier on a measure reference and only rejects it for another table.
if let Some(index) = self.model.measure_index(&name.name.text)
&& let Some(home) = self.model.measures[index].table.as_deref()
{
if self.model.table_index(home) == Some(table_index) {
return Ok(BoundExpr::Measure(index));
}
return Err(BindError::new(format!("measure `{}` belongs to table `{}`, not `{}`", name.name.text, home, table.text), span));
}
return Err(BindError::new(format!("unknown column `{}` in table `{}`", name.name.text, table.text), span));
}
// A bracketed name is always a model object reference (`[Measure]`, `[Column]`), never a
// variable: DAX requires bare identifiers for variables, so `VAR Total = 1 ... [Total]`
// refers to the measure, not the variable.
if name.name.style == crate::NameStyle::Bracketed {
if let Some(index) = self.model.measure_index(&name.name.text) {
return Ok(BoundExpr::Measure(index));
}
// A bracketed name may be a row-context column; the evaluator resolves it.
return Ok(BoundExpr::UnqualifiedColumn { name: name.name.text.clone() });
}
if let Some(index) = vars.iter().rposition(|var| var.eq_ignore_ascii_case(&name.name.text)) {
return Ok(BoundExpr::Variable { index, name: name.name.text.clone() });
}
if let Some(index) = self.model.table_index(&name.name.text) {
return Ok(BoundExpr::Table(index));
}
if let Some(index) = self.model.measure_index(&name.name.text) {
return Ok(BoundExpr::Measure(index));
}
Err(BindError::new(format!("unknown name `{}`", name.name.text), span))
}
fn bind_call(&self, call: &Call, span: crate::Span, vars: &mut Vec<String>) -> Result<BoundExpr, BindError> {
let Some(spec) = lookup(&call.name.text) else {
return Err(BindError::new(format!("unknown DAX function `{}`", call.name.text), span));
};
if let Some(error) = validate_call(call).into_iter().next() {
return Err(BindError::new(error.message, span));
}
let mut args = Vec::with_capacity(call.args.len());
for (index, arg) in call.args.iter().enumerate() {
// Documented enum parameters (intervals, ties, blanks, text type names) are written
// as bare names. The parser cannot tell them from table/measure names, but the
// catalog's parameter kind can: a Text position only accepts a literal or a keyword.
let expected = spec.overload_for(call.args.len()).and_then(|overload| overload.params.get(index)).copied();
let keyword = match spec.name {
"DATATABLE" if index % 2 == 1 => keyword_name(arg),
"CONVERT" if index == 1 => keyword_name(arg),
// RANKX's Ties argument is documented as `Dense` but catalogued as a Scalar.
"RANKX" if index == 4 => keyword_name(arg),
// RANKX's Order argument is catalogued as a Scalar too, but it is `ASC`/`DESC`.
"RANKX" if index == 3 => clause_keyword(arg, &["ASC", "DESC"]),
"DATEDIFF" if index == 2 => keyword_name(arg),
// TOPN's `(expression, Order)` pairs: ASC/DESC sit at every odd index from 3.
"TOPN" if index >= 3 && index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]),
"CROSSFILTER" if index == 2 => {
clause_keyword(arg, &["NONE", "ONE", "ONEWAY", "BOTH", "TWOWAY", "ONEWAY_LEFTFILTERSRIGHT", "ONEWAY_RIGHTFILTERSLEFT"])
}
// RANK/ROWNUMBER's Reset argument is `NONE`, `LOWESTPARENT` or `HIGHESTPARENT`,
// catalogued as `Any` so that a relation expression still binds there.
"RANK" if index == 6 => clause_keyword(arg, &["NONE", "LOWESTPARENT", "HIGHESTPARENT"]),
// The documented bare ASC/DESC slots: RANKX and RANK.EQ take Order at index 3/2,
// TOPNSKIP/CONCATENATEX at index 4 and SAMPLE at index 3.
"RANK.EQ" if index == 2 => clause_keyword(arg, &["ASC", "DESC"]),
// SAMPLE and TOPNSKIP repeat `(orderBy, Order)` pairs, so every order word sits at
// an even offset from the first one: 3, 5, 7, ... for SAMPLE and 4, 6, 8, ... for
// TOPNSKIP.
"TOPNSKIP" if index >= 4 && (index - 4) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
"SAMPLE" if index >= 3 && (index - 3) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
// CONCATENATEX takes `(orderBy, Order)` pairs from index 4 on, so every even
// offset from 4 is an order word.
"CONCATENATEX" if index >= 4 && (index - 4) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
"ROWNUMBER" if index == 5 => clause_keyword(arg, &["NONE", "LOWESTPARENT", "HIGHESTPARENT"]),
// Window/relation clauses take bare enum words: `ORDERBY(x, DESC)`,
// `WINDOW(1, ABS, 1, ABS, ...)`, `INDEX(..., KEEP, PARTITIONBY(...))`, and the
// LOOKUP associated-columns behaviour (`INFERRED`).
"ORDERBY" if index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]),
"INDEX" | "OFFSET" if index >= 2 => clause_keyword(arg, WINDOW_KEYWORDS),
// FromType/ToType are optional, so the blanks/reset slots move with the layout;
// `window_table` identifies each slot by its value.
"WINDOW" if index >= 1 => clause_keyword(arg, WINDOW_KEYWORDS),
"LOOKUP" | "LOOKUPWITHTOTALS" if index % 2 == 1 && index + 1 == call.args.len() => {
clause_keyword(arg, &["EXPLICIT", "INFERRED", "DEFAULT"])
}
// PATHITEM's optional Type is documented as `TEXT`/`INTEGER` but catalogued as
// `Any` so that the numeric `0`/`1` spellings still bind.
"PATHITEM" | "PATHITEMREVERSE" if index == 2 => clause_keyword(arg, &["TEXT", "INTEGER"]),
_ if matches!(expected, Some(ParamKind::Text)) => keyword_name(arg),
_ => visual_keyword_name(spec.name, index, arg),
}
// A name only wins where the position genuinely accepts one — a documented `Text`
// argument such as `RANKX(..., Dense)` or a visual calculation's axis. A fixed enum
// slot (`DATEDIFF`'s interval, `CONVERT`'s type, the order words) is not a name
// position: a table called `Month` must not turn `DATEDIFF(a, b, MONTH)` into a table
// reference, and a variable called `YEAR` must not either.
.filter(|keyword| {
// `DATATABLE`'s type words are types even though the catalog marks them `Text`,
// so a table named `INTEGER` must not capture them either.
let fixed_slot =
spec.name == "DATATABLE" || (!matches!(expected, Some(ParamKind::Text)) && !is_visual_keyword(spec.name, index, keyword));
if fixed_slot {
return true;
}
let named = self.model.table_index(keyword).is_some() || self.model.measure_index(keyword).is_some();
let variable = vars.iter().any(|var| var.eq_ignore_ascii_case(keyword));
!named && !variable
});
if let Some(keyword) = keyword {
args.push(BoundExpr::Keyword(keyword));
} else {
args.push(self.bind_with_vars(arg, vars)?);
}
}
Ok(BoundExpr::Call { spec, args })
}
}
fn keyword_name(expr: &Expr) -> Option<String> {
match &expr.kind {
ExprKind::Name(name) if name.table.is_none() && name.name.style == crate::NameStyle::Bare => Some(name.name.text.clone()),
_ => None,
}
}
/// Bare identifiers that visual-calculation functions accept where their syntax documents an
/// axis, an ORDERBY flag, a blank-ordering enumeration or a reset clause. These words are not
/// names in the model, so they must become [`BoundExpr::Keyword`] instead of failing resolution.
fn visual_keyword_name(function: &str, index: usize, arg: &Expr) -> Option<String> {
let word = keyword_name(arg)?;
is_visual_keyword(function, index, &word).then_some(word)
}
/// Whether `word` is a documented keyword at the 0-based `index` of a visual-calculation call.
///
/// The positions mirror the Microsoft syntax for each function, e.g. `FIRST ( <column>[, <axis>]
/// [, <orderBy>][, <blanks>][, reset] )` and `RANGE ( <step>[, <includeCurrent>][, <axis>]
/// [, <orderBy>][, <blanks>][, <reset>] )`. `COLLAPSE`/`EXPAND` also have navigation-only forms
/// whose first argument is the axis (`COLLAPSE ( <axis>[, N] )`).
fn is_visual_keyword(function: &str, index: usize, word: &str) -> bool {
let axis = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "ROWS" | "COLUMNS");
let order_by = |positions: &[usize]| positions.contains(&index) && word.eq_ignore_ascii_case("KEEP");
let blanks = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "DEFAULT" | "FIRST" | "LAST");
let reset =
|positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "NONE" | "LOWESTPARENT" | "HIGHESTPARENT");
match function {
"COLLAPSE" | "EXPAND" | "COLLAPSEALL" | "EXPANDALL" => axis(&[0, 1]),
"FIRST" | "LAST" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]),
"PREVIOUS" | "NEXT" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]),
"MOVINGAVERAGE" => axis(&[3]) || order_by(&[4]) || blanks(&[5]) || reset(&[6]),
"RUNNINGSUM" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]),
"RANGE" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]),
_ => false,
}
}
/// The enum words accepted by the window/relation clauses. Matching is case-insensitive, and an
/// identifier outside this set is left to normal name binding so typos still report an error.
const WINDOW_KEYWORDS: &[&str] = &["ASC", "DESC", "ABS", "REL", "DEFAULT", "FIRST", "LAST", "KEEP", "NONE", "LOWESTPARENT", "HIGHESTPARENT"];
fn clause_keyword(expr: &Expr, allowed: &[&str]) -> Option<String> {
let word = keyword_name(expr)?;
allowed.iter().any(|candidate| word.eq_ignore_ascii_case(candidate)).then_some(word)
}
fn collect_measure_names(model: &DataModel, expr: &BoundExpr, out: &mut BTreeSet<String>) {
match expr {
BoundExpr::Measure(index) => {
if let Some(measure) = model.measures.get(*index) {
out.insert(measure.name.clone());
}
}
BoundExpr::Call { args, .. } | BoundExpr::TableConstructor(args) | BoundExpr::Tuple(args) => {
for arg in args {
collect_measure_names(model, arg, out);
}
}
BoundExpr::Unary { expr, .. } => collect_measure_names(model, expr, out),
BoundExpr::Binary { left, right, .. } => {
collect_measure_names(model, left, out);
collect_measure_names(model, right, out);
}
BoundExpr::VarReturn { vars, body } => {
for var in vars {
collect_measure_names(model, &var.expr, out);
}
collect_measure_names(model, body, out);
}
BoundExpr::Literal(_)
| BoundExpr::Column { .. }
| BoundExpr::UnqualifiedColumn { .. }
| BoundExpr::Table(_)
| BoundExpr::Variable { .. }
| BoundExpr::Keyword(_) => {}
}
}
/// Parses and binds one measure formula against a model, without requiring a full model parse.
pub fn bind_formula(model: &DataModel, formula: &str) -> Result<BoundExpr, BindError> {
let expr = parse_expression(formula).map_err(|error| BindError::new(error.message, error.span))?;
Binder::new(model).bind_expression(&expr)
}
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
//! Aggregation functions.
//!
//! The core evaluator switch owns `SUM`, `AVERAGE`, `COUNT`, `COUNTA`, `COUNTBLANK`, `MIN`,
//! `MAX`, `PRODUCT` and the `*X` iterators. This module covers the aggregations the core switch
//! leaves out: the `*A` variants, whose text/Boolean coercions differ from their plain
//! counterparts, and `DISTINCTCOUNTNOBLANK`.
//!
//! All four read a column under the current filter context and delegate the arithmetic to
//! [`support::aggregate_values`]. `AVERAGEA` uses every row in the denominator and coerces
//! BLANK to 0 (Microsoft's DAX example averages 1, 20, "n/a", BLANK, TRUE as 22/5), so only a
//! column with no rows at all is BLANK; `DISTINCTCOUNTNOBLANK` drops BLANK before counting
//! distinct values.
#![allow(unused_imports)]
use super::*;
/// Scalar aggregation functions owned by this module.
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
match name.to_ascii_uppercase().as_str() {
"AVERAGEA" | "DISTINCTCOUNTNOBLANK" | "MAXA" | "MINA" => Some(aggregate_column(ev, name, args, ctx)),
_ => None,
}
}
/// Aggregations are scalar-only; none of these names is a table function, so table dispatch
/// never handles one and always returns `None`.
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
None
}
/// Evaluates the single column argument and aggregates it. The catalog gives every function in
/// this module exactly one `Column` parameter, so a missing argument is a programming error the
/// binder already rejected; report it as an ordinary evaluation error all the same.
fn aggregate_column(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let column = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a column")))?;
let values = ev.column_values(column, ctx)?;
super::support::aggregate_values(name, &values)
}
File diff suppressed because it is too large Load Diff
+71
View File
@@ -0,0 +1,71 @@
//! Logical functions.
//!
//! This module owns the engine-only bitwise integer operations and `IF.EAGER`. `IF`, `AND`, `OR`,
//! `NOT`, `COALESCE` and `IFERROR` live in the core evaluator because they need lazy argument
//! evaluation; `IF.EAGER` is the documented opposite: it forces both branches to be evaluated
//! before the condition selects one.
use super::support::{args as arg_values, eval_all};
use super::*;
/// Scalar logical functions owned by this module: the bitwise integer operations and `IF.EAGER`.
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() {
"BITAND" | "BITOR" | "BITXOR" => Some(bitwise(&name, ev, args, ctx)),
"IF.EAGER" => Some(if_eager(ev, args, ctx)),
_ => None,
}
}
/// Logical functions are scalar-only; none of these names is a table function, so this module
/// never handles table dispatch and always returns `None`.
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
None
}
/// Evaluates `BITAND`, `BITOR` or `BITXOR` with both arguments forced, truncating each operand
/// to a 64-bit integer before applying the operation. A native `Integer` stays exact: converting
/// it through `f64` would lose bits above 2^53.
fn bitwise(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);
let left = bit_operand(a.arg(0)?, name, 0)?;
let right = bit_operand(a.arg(1)?, name, 1)?;
let result = match name {
"BITAND" => left & right,
"BITOR" => left | right,
"BITXOR" => left ^ right,
_ => return Err(EvalError::new(format!("{name} is not a bitwise function"))),
};
Ok(Scalar::Integer(result))
}
/// Bit operations use the truncated two's-complement `i64` value; DAX documents a signed 64-bit
/// result, so negative operands participate through their two's-complement representation.
///
/// A native `Integer` is used as-is so whole numbers above 2^53 keep every bit. Other numeric
/// variants are converted to `f64` (already lossy above 2^53 for `Decimal`) and truncated.
fn bit_operand(value: &Scalar, name: &str, index: usize) -> Result<i64, EvalError> {
if let Scalar::Integer(integer) = value {
return Ok(*integer);
}
let number = value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))?;
if !number.is_finite() || number.trunc() < -9_223_372_036_854_775_808.0 || number.trunc() >= 9_223_372_036_854_775_808.0 {
return Err(EvalError::new(format!("{name} argument {} is outside the 64-bit integer range", index + 1)));
}
Ok(number.trunc() as i64)
}
/// `IF.EAGER` evaluates the condition and both branch expressions before choosing a result, so an
/// error in the branch that would not be selected still propagates.
fn if_eager(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
let values = eval_all(ev, args, ctx)?;
let a = arg_values("IF.EAGER", &values);
let condition = a.boolean(0)?;
let when_true = a.arg(1)?;
if condition {
return Ok(when_true.clone());
}
Ok(a.optional(2).cloned().unwrap_or(Scalar::Blank))
}
File diff suppressed because it is too large Load Diff
+765
View File
@@ -0,0 +1,765 @@
//! Shared helpers for the category-specific function implementations.
//!
//! Each function family lives in its own module (`financial`, `statistical`, ...) and exposes a
//! `call`/`call_table` dispatcher. Those dispatchers receive the unevaluated arguments and the
//! evaluator's [`Context`](super::Context), so they can choose lazy or eager evaluation and can
//! push row frames for iterators. This module holds the small, boring pieces they share: scalar
//! argument coercion, Excel date serials, rounding and row-frame construction.
#![allow(dead_code)] // helpers are consumed by the per-family modules as they land
use std::cell::RefCell;
use std::cmp::Ordering;
use super::*;
use chrono::{Datelike, NaiveDate};
/// The evaluated arguments of a scalar function call.
pub(crate) struct Args<'a> {
pub(crate) name: &'a str,
pub(crate) values: &'a [Scalar],
}
impl<'a> Args<'a> {
pub(crate) fn arg(&self, index: usize) -> Result<&'a Scalar, EvalError> {
self.values.get(index).ok_or_else(|| EvalError::new(format!("{} is missing argument {}", self.name, index + 1)))
}
pub(crate) fn optional(&self, index: usize) -> Option<&'a Scalar> {
self.values.get(index)
}
pub(crate) fn number(&self, index: usize) -> Result<f64, EvalError> {
self.arg(index)?.to_number().ok_or_else(|| EvalError::new(format!("{} argument {} must be numeric", self.name, index + 1)))
}
pub(crate) fn int(&self, index: usize) -> Result<i64, EvalError> {
Ok(self.number(index)? as i64)
}
pub(crate) fn text(&self, index: usize) -> Result<String, EvalError> {
Ok(self.arg(index)?.to_text())
}
pub(crate) fn boolean(&self, index: usize) -> Result<bool, EvalError> {
self.arg(index)?.to_bool().ok_or_else(|| EvalError::new(format!("{} argument {} must be Boolean", self.name, index + 1)))
}
pub(crate) fn date(&self, index: usize) -> Result<f64, EvalError> {
let value = self.number(index)?;
if !value.is_finite() {
return Err(EvalError::new(format!("{} argument {} must be a date", self.name, index + 1)));
}
Ok(value)
}
pub(crate) fn optional_number(&self, index: usize, default: f64) -> Result<f64, EvalError> {
match self.values.get(index) {
Some(value) if !value.is_blank() => {
value.to_number().ok_or_else(|| EvalError::new(format!("{} argument {} must be numeric", self.name, index + 1)))
}
_ => Ok(default),
}
}
pub(crate) fn optional_bool(&self, index: usize, default: bool) -> Result<bool, EvalError> {
match self.values.get(index) {
Some(value) if !value.is_blank() => {
value.to_bool().ok_or_else(|| EvalError::new(format!("{} argument {} must be Boolean", self.name, index + 1)))
}
_ => Ok(default),
}
}
}
/// Evaluates every argument eagerly, left to right.
pub(crate) fn eval_all(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Vec<Scalar>, EvalError> {
args.iter().map(|arg| ev.eval(arg, ctx)).collect()
}
/// Evaluates one argument as a table.
pub(crate) fn eval_table(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &mut Context) -> Result<TableValue, EvalError> {
ev.eval_table(expr, ctx)
}
/// Builds a row frame for one row of a table value, mapping columns back to the model by name
/// when the table keeps its lineage.
pub(crate) fn frame_for(ev: &Evaluator<'_>, table: &TableValue, row: &[Scalar]) -> RowFrame {
let names: Vec<String> = table.columns.iter().map(|column| column.name.clone()).collect();
let model_columns: Vec<Option<usize>> = match table.lineage {
Some(lineage) => names.iter().map(|name| ev.model().column_index(lineage, name)).collect(),
None => vec![None; names.len()],
};
RowFrame { lineage: table.lineage, names, values: row.to_vec(), model_columns }
}
/// Builds a frame for a plain model table row whose values follow the model column order.
pub(crate) fn model_row_frame(ev: &Evaluator<'_>, table: usize, values: Vec<Scalar>) -> RowFrame {
let names: Vec<String> =
ev.model().tables.get(table).map(|table| table.columns.iter().map(|column| column.name.clone()).collect()).unwrap_or_default();
let model_columns: Vec<Option<usize>> = (0..names.len()).map(Some).collect();
RowFrame { lineage: Some(table), names, values, model_columns }
}
/// Builds a frame for a derived table row whose columns are given explicitly.
pub(crate) fn derived_row_frame(lineage: Option<usize>, names: Vec<String>, values: Vec<Scalar>, model_columns: Vec<Option<usize>>) -> RowFrame {
RowFrame { lineage, names, values, model_columns }
}
/// Eagerly evaluated scalar argument access for functions that already hold `Vec<Scalar>`.
pub(crate) fn args<'a>(name: &'a str, values: &'a [Scalar]) -> Args<'a> {
Args { name, values }
}
/// Orders two scalars for sorting: deterministic, transitive and total over every variant.
///
/// [`Scalar::compare`] follows DAX's `=`/`<` coercion rules and answers `None` for pairs DAX
/// does not compare: text against a number, and anything against NaN. A sort cannot read `None`
/// as equality, because text would then equal every number while the numbers still order among
/// themselves — not a total order, which `sort_by` may panic on (Rust 1.81+).
///
/// This ordering ranks whole classes instead, so mixed columns sort predictably:
///
/// 1. numbers (`Integer`, `Currency`, `Decimal`, `DateTime`) by numeric value, through
/// `f64::total_cmp`, so NaN has a fixed place (after every other number) and `-0.0` sorts
/// before `0.0`;
/// 2. text, case-insensitively (Unicode lowercase, matching [`Scalar::compare`]); strings equal
/// under lowercasing tie-break on the raw strings, so `"A"` and `"a"` still have a fixed
/// order;
/// 3. Booleans, `FALSE` before `TRUE`.
///
/// BLANK is the caller's business. Callers with a blank placement policy (`FIRST`/`LAST` in
/// `RANK`/`ROWNUMBER`, the blank-aware window ordering) place blanks before calling. A blank
/// that does reach this function orders as the number zero, which is DAX's default comparison
/// and keeps the order transitive.
pub(crate) fn total_order(left: &Scalar, right: &Scalar) -> Ordering {
fn class(value: &Scalar) -> u8 {
match value {
Scalar::String(_) => 1,
Scalar::Boolean(_) => 2,
Scalar::Blank | Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_) => 0,
}
}
// BLANK counts as zero, as in DAX's default comparison; every other number-class variant has
// a numeric value, so the NaN fallback is unreachable but keeps the function total.
fn number(value: &Scalar) -> f64 {
value.to_number().unwrap_or(f64::NAN)
}
match class(left).cmp(&class(right)) {
Ordering::Equal => match (left, right) {
(Scalar::String(a), Scalar::String(b)) => a.to_lowercase().cmp(&b.to_lowercase()).then_with(|| a.cmp(b)),
(Scalar::Boolean(a), Scalar::Boolean(b)) => a.cmp(b),
_ => number(left).total_cmp(&number(right)),
},
ordering => ordering,
}
}
/// 400 Gregorian years, after which the calendar (and every month length) repeats.
const GREGORIAN_CYCLE_DAYS: i64 = 146_097;
/// chrono counts days from 0001-01-01; 1970-01-01 is the 719,163rd of them.
const UNIX_EPOCH_CE_DAYS: i64 = 719_163;
/// Excel/OLE serial 0 is 1899-12-30, which is 25,569 days before 1970-01-01.
const UNIX_EPOCH_SERIAL: i64 = 25_569;
/// The CE day of Excel/OLE serial 0 (1899-12-30): `UNIX_EPOCH_CE_DAYS - UNIX_EPOCH_SERIAL`.
const EXCEL_EPOCH_CE_DAYS: i64 = 693_594;
/// Excel/OLE date serial for a calendar date and time. Dates before 1900-03-01 ignore the
/// 1900 leap-year compatibility bug; DAX/Excel only differ there.
pub(crate) fn date_serial(year: i64, month: i64, day: i64, hour: i64, minute: i64, second: i64) -> f64 {
// Normalize out-of-range months the way Excel does (DATE(2024, 13, 1) is 2025-01-01). The day
// counts on from the first of that month, so day 0 is the last day of the month before.
let months = month - 1;
let year = year.saturating_add(months.div_euclid(12));
let month = u32::try_from(months.rem_euclid(12) + 1).unwrap_or(1);
let days = month_start_ce_days(year, month) - i128::from(EXCEL_EPOCH_CE_DAYS) + i128::from(day) - 1;
days as f64 + (hour as f64 * 3600.0 + minute as f64 * 60.0 + second as f64) / 86400.0
}
/// Calendar date of an Excel/OLE date serial's whole days.
pub(crate) fn date_parts(serial: f64) -> (i64, i64, i64) {
let unix = (serial.floor() as i64).saturating_sub(UNIX_EPOCH_SERIAL);
// The calendar repeats every 400 years (146,097 days), so chrono converts the day within its
// cycle and the whole cycles go back into the year (AGENTS.md).
let (cycles, rest) = (unix.div_euclid(GREGORIAN_CYCLE_DAYS), unix.rem_euclid(GREGORIAN_CYCLE_DAYS));
match i32::try_from(rest + UNIX_EPOCH_CE_DAYS).ok().and_then(NaiveDate::from_num_days_from_ce_opt) {
Some(date) => {
let year = i128::from(date.year()) + i128::from(cycles) * 400;
let year = i64::try_from(year).unwrap_or(if year < 0 { i64::MIN } else { i64::MAX });
(year, i64::from(date.month()), i64::from(date.day()))
}
// Unreachable: `rest + 719_163` is always a valid CE day.
None => (1970, 1, 1),
}
}
/// Number of days in a calendar month, `30` for a month outside 1–12 (the value the caller expects
/// for a month the evaluator has already normalized).
pub(crate) fn days_in_month(year: i64, month: i64) -> i64 {
if !(1..=12).contains(&month) {
return 30;
}
// The month's length repeats with the 400-year cycle, so the year within it answers and always
// fits `NaiveDate`.
let year = year.rem_euclid(400) as i32;
let month = month as u32;
let first = |year: i32, month: u32| NaiveDate::from_ymd_opt(year, month, 1);
match (first(year, month), if month == 12 { first(year + 1, 1) } else { first(year, month + 1) }) {
(Some(start), Some(next)) => (next - start).num_days(),
// Unreachable: the year is in 0..=399 and the month is 1..=12.
_ => 30,
}
}
/// Whether a year is a Gregorian leap year, for every `i64` year.
pub(crate) fn is_leap_year(year: i64) -> bool {
// Leap years repeat every 400 years, so the year within its cycle decides and always fits
// `NaiveDate`: 29 February exists exactly in a leap year.
NaiveDate::from_ymd_opt(year.rem_euclid(400) as i32, 2, 29).is_some()
}
/// Days since 0001-01-01 (chrono's `num_days_from_ce`) of the first day of a calendar month, for
/// every `i64` year. Whole 400-year Gregorian cycles are added back as days.
fn month_start_ce_days(year: i64, month: u32) -> i128 {
let cycles = i128::from(year.div_euclid(400));
let year = year.rem_euclid(400) as i32;
match NaiveDate::from_ymd_opt(year, month, 1) {
Some(first) => i128::from(first.num_days_from_ce()) + cycles * i128::from(GREGORIAN_CYCLE_DAYS),
// Unreachable: the year within its cycle is in 0..=399 and the month is 1..=12.
None => i128::from(NaiveDate::MIN.num_days_from_ce()),
}
}
pub(crate) fn date_weekday(serial: f64) -> i64 {
let days = serial.floor() as i64;
let weekday = days.rem_euclid(7);
if weekday == 0 { 7 } else { weekday }
}
/// The year and month `months` away from the month of `serial`, or `None` when the shift leaves
/// the years Excel dates can represent.
///
/// The month total is computed in `i128`: `months` arrives from `number(..) as i64`, which saturates
/// at `i64::MAX`, and `year * 12 + month - 1 + months` would wrap (or panic in debug builds) for
/// such an argument.
fn shift_month(serial: f64, months: i64) -> Option<(i64, i64)> {
let (year, month, _) = date_parts(serial);
let total = i128::from(year) * 12 + i128::from(month) - 1 + i128::from(months);
let year = i64::try_from(total.div_euclid(12)).ok()?;
if !(1..=9999).contains(&year) {
return None;
}
Some((year, i64::try_from(total.rem_euclid(12)).ok()? + 1))
}
pub(crate) fn eomonth(serial: f64, months: i64) -> f64 {
match shift_month(serial, months) {
Some((year, month)) => date_serial(year, month, days_in_month(year, month), 0, 0, 0),
// A shift Excel cannot represent leaves the date where it was instead of wrapping.
None => serial,
}
}
pub(crate) fn edate(serial: f64, months: i64) -> f64 {
let (_, _, day) = date_parts(serial);
match shift_month(serial, months) {
Some((year, month)) => date_serial(year, month, day.min(days_in_month(year, month)), 0, 0, 0),
None => serial,
}
}
/// The local date as an Excel serial (TODAY).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn today_serial() -> f64 {
now_serial().floor()
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn today_serial() -> f64 {
now_serial().floor()
}
/// The browser clock as an Excel serial, the wasm arm of [`now_serial`]/[`utc_now_serial`].
///
/// The standard library's clock traps on wasm, so the epoch comes from `js_sys::Date`, the same
/// source `crates/core/src/date.rs` uses. `Date::now()` is UTC milliseconds; for the local serial
/// the browser's time-zone offset is subtracted (it counts minutes *west* of UTC), and only
/// `TODAY`/`UTCTODAY` floor the result.
#[cfg(target_arch = "wasm32")]
fn wasm_now_serial(local: bool) -> f64 {
const MILLISECONDS_PER_DAY: f64 = 86_400_000.0;
let offset_minutes = if local { -js_sys::Date::new_0().get_timezone_offset() } else { 0.0 };
25569.0 + js_sys::Date::now() / MILLISECONDS_PER_DAY + offset_minutes / 1_440.0
}
/// The local date and time as an Excel serial (NOW).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn now_serial() -> f64 {
use chrono::{Datelike, Timelike};
let now = chrono::Local::now();
date_serial(
i64::from(now.year()),
i64::from(now.month()),
i64::from(now.day()),
i64::from(now.hour()),
i64::from(now.minute()),
i64::from(now.second()),
) + f64::from(now.nanosecond()) / 86_400_000_000_000.0
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn now_serial() -> f64 {
wasm_now_serial(true)
}
/// The UTC date and time as an Excel serial (UTCNOW).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn utc_now_serial() -> f64 {
use chrono::{Datelike, Timelike};
let now = chrono::Utc::now();
date_serial(
i64::from(now.year()),
i64::from(now.month()),
i64::from(now.day()),
i64::from(now.hour()),
i64::from(now.minute()),
i64::from(now.second()),
) + f64::from(now.nanosecond()) / 86_400_000_000_000.0
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn utc_now_serial() -> f64 {
wasm_now_serial(false)
}
/// The UTC date at midnight as an Excel serial (UTCTODAY).
pub(crate) fn utc_today_serial() -> f64 {
utc_now_serial().floor()
}
/// Rounds `value` to 15 significant digits, the precision Excel and DAX compute with.
///
/// `value * 10^digits` carries the binary representation error of its factors, and a directed
/// rounding makes that error visible: `0.29 * 100` is `28.999999999999996`, so `ROUNDDOWN ( 0.29,
/// 2 )` would truncate to `0.28` and `ROUNDUP ( 0.07, 2 )` would ceil `7.000000000000001` to
/// `0.08`. Snap that noise away before rounding, exactly as `to_dax_text` does when it prints.
fn excel_precision(value: f64) -> f64 {
// An exact whole number under 2^53 has no binary noise to remove, and snapping it would drop
// digits: `ROUND ( 1234567890123457, 0 )` must stay that number.
if is_exact_whole(value) {
return value;
}
format!("{value:.14e}").parse().unwrap_or(value)
}
/// Whether `value` is a whole number held exactly in an `f64`.
fn is_exact_whole(value: f64) -> bool {
value.fract() == 0.0 && value.abs() < 2f64.powi(53)
}
pub(crate) fn round_to(value: f64, digits: i32) -> f64 {
// The scale factor overflows or underflows outside f64's exponent range: past +308 digits the
// value cannot change, past -308 every digit is rounded away.
if digits > 308 {
return value;
}
if digits < -308 {
return 0.0;
}
// An exact whole number is already rounded: scaling it past 2^53 would only make the snap
// lose digits, so `ROUND ( 1234567890123457, 1 )` stays that number.
if digits >= 0 && is_exact_whole(value) {
return value;
}
let factor = 10f64.powi(digits);
let scaled = excel_precision(value * factor);
if !scaled.is_finite() {
return value;
}
scaled.round() / factor
}
/// ROUNDUP/ROUNDDOWN: `up` rounds away from zero, otherwise toward zero. Excel and DAX define
/// both in terms of the sign, not the floor/ceiling, so `ROUNDDOWN ( -2.9, 0 )` is -2 and
/// `ROUNDUP ( -2.1, 0 )` is -3.
pub(crate) fn round_direction(value: f64, digits: i32, up: bool) -> f64 {
// `10^digits` overflows or underflows outside f64's exponent range; the result is the value
// itself when rounding cannot move any digit, and zero when every digit is rounded away.
if digits > 308 {
return value;
}
if digits < -308 {
return if up && value != 0.0 { f64::INFINITY.copysign(value) } else { 0.0 };
}
if digits >= 0 && is_exact_whole(value) {
return value;
}
let factor = 10f64.powi(digits);
let scaled = excel_precision(value * factor);
if !scaled.is_finite() {
return value;
}
let rounded = if up { scaled.abs().ceil().copysign(scaled) } else { scaled.trunc() };
rounded / factor
}
/// The greatest common divisor of the two magnitudes, so `i64::MIN` is represented without
/// overflowing the way `i64::abs` would.
pub(crate) fn gcd(a: i64, b: i64) -> u64 {
let (mut a, mut b) = (a.unsigned_abs(), b.unsigned_abs());
while b != 0 {
let t = a % b;
a = b;
b = t;
}
a
}
/// The least common multiple, or `None` when it does not fit in an `i64` (Excel answers `#NUM!`).
pub(crate) fn lcm(a: i64, b: i64) -> Option<i64> {
if a == 0 || b == 0 {
return Some(0);
}
(a.unsigned_abs() / gcd(a, b)).checked_mul(b.unsigned_abs()).and_then(|value| i64::try_from(value).ok())
}
/// Applies a scalar aggregation over already-evaluated values.
pub(crate) fn aggregate_values(name: &str, values: &[Scalar]) -> Result<Scalar, EvalError> {
// Plain aggregations take numeric values only: DAX specifies that SUM/AVERAGE/MIN/MAX/PRODUCT
// ignore logicals and text instead of coercing them. The `*A` variants below keep their own
// coercion and read `values` directly.
let numbers: Vec<f64> = values
.iter()
.filter(|value| matches!(value, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_)))
.filter_map(Scalar::to_number)
.collect();
match name.to_ascii_uppercase().as_str() {
"SUM" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().sum()) }),
"AVERAGE" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().sum::<f64>() / numbers.len() as f64) }),
"AVERAGEA" => {
// Every row counts: text (numeric or not) counts as 0, TRUE/FALSE as 1/0, and a BLANK
// cell as 0, so it stays in the denominator — Microsoft's example averages 1, 20,
// "n/a", BLANK and TRUE as 22/5. A column with no rows at all is BLANK.
if values.is_empty() {
return Ok(Scalar::Blank);
}
let sum: f64 = values
.iter()
.map(|value| match value {
Scalar::String(_) => 0.0,
Scalar::Boolean(value) => f64::from(u8::from(*value)),
other => other.to_number().unwrap_or(0.0),
})
.sum();
Ok(Scalar::Decimal(sum / values.len() as f64))
}
"PRODUCT" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().product()) }),
"MIN" | "MAX" => {
// The winner keeps its own type — a date column answers a DateTime and an integer
// column an Integer — so this cannot read the `f64` projection the sum-like
// aggregations use. Only numbers compete: text and logicals are not observations.
let want = if name.eq_ignore_ascii_case("MIN") { Ordering::Less } else { Ordering::Greater };
let mut best: Option<&Scalar> = None;
for value in
values.iter().filter(|value| matches!(value, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_)))
{
match best {
None => best = Some(value),
Some(current) if value.compare(current) == Some(want) => best = Some(value),
Some(_) => {}
}
}
Ok(best.cloned().unwrap_or(Scalar::Blank))
}
"MINA" => Ok(values
.iter()
.filter(|value| !value.is_blank())
.map(|value| match value {
Scalar::String(_) => 0.0,
Scalar::Boolean(value) => f64::from(u8::from(*value)),
other => other.to_number().unwrap_or(0.0),
})
.reduce(f64::min)
.map(Scalar::Decimal)
.unwrap_or(if values.is_empty() { Scalar::Blank } else { Scalar::Decimal(0.0) })),
"MAXA" => Ok(values
.iter()
.filter(|value| !value.is_blank())
.map(|value| match value {
Scalar::String(_) => 0.0,
Scalar::Boolean(value) => f64::from(u8::from(*value)),
other => other.to_number().unwrap_or(0.0),
})
.reduce(f64::max)
.map(Scalar::Decimal)
.unwrap_or(if values.is_empty() { Scalar::Blank } else { Scalar::Decimal(0.0) })),
"COUNT" => {
let count = values.iter().filter(|v| !v.is_blank() && !matches!(v, Scalar::Boolean(_))).count();
Ok(if count == 0 { Scalar::Blank } else { Scalar::Integer(count as i64) })
}
"COUNTA" => {
let count = values.iter().filter(|v| !v.is_blank()).count();
Ok(if count == 0 { Scalar::Blank } else { Scalar::Integer(count as i64) })
}
"COUNTBLANK" => Ok(Scalar::Integer(values.iter().filter(|v| v.is_blank() || v.to_text().is_empty()).count() as i64)),
"DISTINCTCOUNT" | "APPROXIMATEDISTINCTCOUNT" => {
let distinct: BTreeSet<ScalarKey> = values.iter().map(distinct_key).collect();
Ok(if values.is_empty() { Scalar::Blank } else { Scalar::Integer(distinct.len() as i64) })
}
"DISTINCTCOUNTNOBLANK" => {
let distinct: BTreeSet<ScalarKey> = values.iter().filter(|value| !value.is_blank()).map(distinct_key).collect();
Ok(Scalar::Integer(distinct.len() as i64))
}
_ => Err(EvalError::not_implemented(name)),
}
}
/// Coerces a scalar to a date serial, treating blanks as 0.
pub(crate) fn date_value(value: &Scalar) -> Option<f64> {
match value {
Scalar::DateTime(serial) => Some(*serial),
Scalar::String(text) => parse_date_text(text),
Scalar::Blank => None,
other => other.to_number(),
}
}
/// Parses the common textual date forms Excel accepts (`YYYY-MM-DD`, `MM/DD/YYYY`,
/// `YYYY-MM-DDTHH:MM:SS`). Locale-specific `DD/MM/YYYY` is deliberately ambiguous and rejected.
/// A component outside the calendar (month 13, 30 February) is rejected rather than rolled over.
pub(crate) fn parse_date_text(text: &str) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
let (date, time) = match text.split_once(['T', ' ']) {
Some((date, time)) => (date, Some(time)),
None => (text, None),
};
let parts: Vec<&str> = date.split(['-', '/']).collect();
let (year, month, day) = match parts.as_slice() {
[first, second, third] => {
let first_value: i64 = first.parse().ok()?;
let second_value: i64 = second.parse().ok()?;
let third_value: i64 = third.parse().ok()?;
// A four-digit leading part is `YYYY-MM-DD`; anything else is `MM/DD/YYYY`.
let (year, month, day) =
if first.len() >= 4 { (first_value, second_value, third_value) } else { (third_value, first_value, second_value) };
let year = if year < 100 { year + if year < 30 { 2000 } else { 1900 } } else { year };
if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
return None;
}
(year, month, day)
}
_ => return None,
};
let (hour, minute, second) = match time.map(str::trim).filter(|time| !time.is_empty()) {
None => (0, 0, 0),
Some(time) => {
// `datetime_text` prints a date as `M/D/YYYY H:MM:SS AM/PM`, so the form the crate
// itself writes has to parse back. The suffix decides the half of the day and the
// hour is then 1-12; without it the hour is 0-23.
let (clock, meridiem) = match time.rsplit_once(' ') {
Some((clock, suffix)) if suffix.eq_ignore_ascii_case("AM") || suffix.eq_ignore_ascii_case("PM") => {
(clock.trim(), Some(suffix.eq_ignore_ascii_case("PM")))
}
_ => (time, None),
};
// A present time must parse and be in range: `25:00:00` is rejected rather than
// rolled into the next day, like an impossible date.
let parts: Vec<&str> = clock.split(':').collect();
let hour: i64 = parts.first()?.trim().parse().ok()?;
let minute: i64 = parts.get(1).unwrap_or(&"0").trim().parse().ok()?;
let second: i64 = parts.get(2).unwrap_or(&"0").trim().parse().ok()?;
let hour = match meridiem {
// 12 AM is midnight and 12 PM is noon; the other PM hours move to the afternoon.
Some(pm) if (1..=12).contains(&hour) => match (hour, pm) {
(12, false) => 0,
(12, true) => 12,
(hour, true) => hour + 12,
(hour, false) => hour,
},
Some(_) => return None,
None => hour,
};
if !(0..24).contains(&hour) || !(0..60).contains(&minute) || !(0..60).contains(&second) {
return None;
}
(hour, minute, second)
}
};
Some(date_serial(year, month, day, hour, minute, second))
}
/// Current evaluation frame's innermost row frame, if any.
pub(crate) fn current_frame(ctx: &Context) -> Option<&RowFrame> {
ctx.rows.last()
}
thread_local! {
/// Columns that are rolled up (blanked) in the `SUMMARIZE` row currently being evaluated.
/// `None` outside a `SUMMARIZE` expression, so `ISSUBTOTAL` can tell "detail row" from "not in
/// a `SUMMARIZE` at all". The state lives here, next to the evaluator's other row-context
/// state, because the function that reads it (`ISSUBTOTAL`) and the one that writes it
/// (`SUMMARIZE`) ship in different evaluator families.
static SUBTOTAL_COLUMNS: RefCell<Option<Vec<(usize, usize)>>> = const { RefCell::new(None) };
}
/// The rolled-up columns of the `SUMMARIZE` row being evaluated, or `None` outside `SUMMARIZE`.
pub(crate) fn subtotal_columns() -> Option<Vec<(usize, usize)>> {
SUBTOTAL_COLUMNS.with(|columns| columns.borrow().clone())
}
/// Pushes the rolled-up columns for one `SUMMARIZE` row and restores the outer state on drop, so
/// a nested `SUMMARIZE` and an error path both leave the context as they found it.
pub(crate) struct SubtotalGuard(Option<Vec<(usize, usize)>>);
impl SubtotalGuard {
pub(crate) fn push(columns: Vec<(usize, usize)>) -> Self {
let previous = SUBTOTAL_COLUMNS.with(|current| current.borrow_mut().replace(columns));
SubtotalGuard(previous)
}
}
impl Drop for SubtotalGuard {
fn drop(&mut self) {
let previous = self.0.take();
SUBTOTAL_COLUMNS.with(|current| *current.borrow_mut() = previous);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serials_round_trip_through_chrono() {
// Serial 0 is 1899-12-30 and 25,569 is 1970-01-01.
assert_eq!(date_serial(1899, 12, 30, 0, 0, 0), 0.0);
assert_eq!(date_serial(1970, 1, 1, 0, 0, 0), 25_569.0);
assert_eq!(date_parts(0.0), (1899, 12, 30));
assert_eq!(date_parts(25_569.0), (1970, 1, 1));
// Leap days exist exactly in leap years.
assert_eq!(date_serial(2024, 2, 29, 0, 0, 0), 45_351.0);
assert_eq!(date_parts(45_351.0), (2024, 2, 29));
assert_eq!(date_serial(2000, 2, 29, 0, 0, 0), date_serial(2000, 3, 1, 0, 0, 0) - 1.0);
// A time of day is a fraction of the serial.
assert_eq!(date_serial(1970, 1, 1, 12, 0, 0), 25_569.5);
assert_eq!(date_parts(25_569.75), (1970, 1, 1));
}
#[test]
fn serial_helpers_extend_past_chronos_year_range() {
// 400 Gregorian years are 146,097 days, so year 400,000 is 999 cycles after year 400.
let cycles = 999.0 * 146_097.0;
assert_eq!(date_serial(400_000, 1, 1, 0, 0, 0) - cycles, date_serial(400, 1, 1, 0, 0, 0));
assert_eq!(date_parts(date_serial(400_000, 2, 29, 0, 0, 0)), (400_000, 2, 29));
// The cycle repeats leap-year and month-length rules too.
assert!(is_leap_year(400_000));
assert!(!is_leap_year(300_100));
assert_eq!(days_in_month(400_000, 2), 29);
assert_eq!(days_in_month(300_100, 2), 28);
}
#[test]
fn out_of_range_months_and_days_roll_over_like_date() {
// DATE(2024, 13, 1) is 2025-01-01 and day 0 is the last day of the previous month.
assert_eq!(date_serial(2024, 13, 1, 0, 0, 0), date_serial(2025, 1, 1, 0, 0, 0));
assert_eq!(date_serial(2024, 0, 1, 0, 0, 0), date_serial(2023, 12, 1, 0, 0, 0));
assert_eq!(date_serial(2024, 3, 0, 0, 0, 0), date_serial(2024, 2, 29, 0, 0, 0));
assert_eq!(days_in_month(2024, 2), 29);
assert_eq!(days_in_month(2023, 2), 28);
assert_eq!(days_in_month(1900, 2), 28);
assert_eq!(days_in_month(2000, 2), 29);
}
#[test]
fn plain_aggregations_ignore_text_logicals_and_blanks() {
// DAX specifies that SUM/AVERAGE/MIN/MAX/PRODUCT use the numeric rows only: text (even
// numeric text), logicals and BLANK are ignored, unlike the `*A` variants.
let values = [
Scalar::Integer(2),
Scalar::String("3".into()),
Scalar::Boolean(true),
Scalar::Blank,
Scalar::Decimal(0.5),
Scalar::Currency(15_000),
Scalar::DateTime(10.0),
];
assert_eq!(aggregate_values("SUM", &values).expect("SUM"), Scalar::Decimal(14.0));
assert_eq!(aggregate_values("AVERAGE", &values).expect("AVERAGE"), Scalar::Decimal(3.5));
// MIN/MAX return the winning value itself: its type survives, so the 10.0 date stays a
// DateTime rather than becoming a decimal serial.
assert_eq!(aggregate_values("MIN", &values).expect("MIN"), Scalar::Decimal(0.5));
assert_eq!(aggregate_values("MAX", &values).expect("MAX"), Scalar::DateTime(10.0));
assert_eq!(aggregate_values("PRODUCT", &values).expect("PRODUCT"), Scalar::Decimal(15.0));
let integers = [Scalar::Integer(7), Scalar::Integer(3), Scalar::Blank];
assert_eq!(aggregate_values("MIN", &integers).expect("MIN"), Scalar::Integer(3));
assert_eq!(aggregate_values("MAX", &integers).expect("MAX"), Scalar::Integer(7));
// A column holding only text, logicals and blanks has no numeric observations at all.
let non_numeric = [Scalar::String("5".into()), Scalar::Boolean(false), Scalar::Blank];
assert_eq!(aggregate_values("SUM", &non_numeric).expect("SUM"), Scalar::Blank);
assert_eq!(aggregate_values("AVERAGE", &non_numeric).expect("AVERAGE"), Scalar::Blank);
// The `*A` variants keep their own coercion: text counts as 0 and TRUE as 1.
assert_eq!(aggregate_values("MINA", &non_numeric).expect("MINA"), Scalar::Decimal(0.0));
assert_eq!(aggregate_values("COUNTA", &non_numeric).expect("COUNTA"), Scalar::Integer(2));
}
#[test]
fn date_text_parses_month_first_and_rejects_impossible_dates() {
// `MM/DD/YYYY`: the leading part is the month, not the year.
assert_eq!(parse_date_text("1/8/2009"), Some(39_821.0));
assert_eq!(parse_date_text("1/8/09"), Some(39_821.0));
// ISO order, and a trailing time is kept.
assert_eq!(parse_date_text("2024-01-15"), Some(45_306.0));
assert_eq!(parse_date_text("2024-01-15T06:00:00"), Some(45_306.25));
// Out-of-range components are rejected instead of rolling over.
assert_eq!(parse_date_text("2024-02-30"), None);
assert_eq!(parse_date_text("13/1/2024"), None);
assert_eq!(parse_date_text("2024-00-10"), None);
assert_eq!(parse_date_text("2023-02-29"), None);
assert_eq!(parse_date_text("1/8"), None);
assert_eq!(parse_date_text(""), None);
}
#[test]
fn date_text_round_trips_the_ampm_form_the_crate_prints() {
// `datetime_text` writes `M/D/YYYY H:MM:SS AM/PM`, so the same text has to parse back:
// 12 AM is midnight and 12 PM is noon, and the other PM hours move to the afternoon.
assert_eq!(parse_date_text("1/2/2024 12:00:00 AM"), Some(date_serial(2024, 1, 2, 0, 0, 0)));
assert_eq!(parse_date_text("1/2/2024 12:00:00 PM"), Some(date_serial(2024, 1, 2, 12, 0, 0)));
assert_eq!(parse_date_text("1/2/2024 1:30:15 PM"), Some(date_serial(2024, 1, 2, 13, 30, 15)));
assert_eq!(parse_date_text("1/2/2024 1:30:15 AM"), Some(date_serial(2024, 1, 2, 1, 30, 15)));
// A suffixed hour is 1-12, so 13 PM and 0 AM are impossible rather than 13:00 and 00:00.
assert_eq!(parse_date_text("1/2/2024 13:00:00 PM"), None);
assert_eq!(parse_date_text("1/2/2024 0:00:00 AM"), None);
}
#[test]
fn rounding_snaps_binary_noise_at_fifteen_digits() {
// `value * 100` carries the binary error of the input, and a directed rounding exposes it.
assert_eq!(round_to(1.005, 2), 1.01);
assert_eq!(round_direction(0.29, 2, false), 0.29);
assert_eq!(round_direction(0.07, 2, true), 0.07);
// The ordinary cases still behave: sign-aware directed rounding and half away from zero.
assert_eq!(round_direction(-2.9, 0, false), -2.0);
assert_eq!(round_direction(-2.1, 0, true), -3.0);
assert_eq!(round_to(2.5, 0), 3.0);
assert_eq!(round_to(2.345, 2), 2.35);
// An exact whole input is already the answer: scaling it past 2^53 must not snap digits.
assert_eq!(round_to(1_234_567_890_123_457.0, 1), 1_234_567_890_123_457.0);
assert_eq!(round_direction(1_234_567_890_123_457.0, 2, true), 1_234_567_890_123_457.0);
}
#[test]
fn gcd_and_lcm_report_results_that_do_not_fit() {
assert_eq!(gcd(12, 18), 6);
// `i64::MIN` has no positive counterpart: the magnitudes are used instead of `abs`.
assert_eq!(gcd(i64::MIN, 2), 2);
assert_eq!(lcm(4, 6), Some(12));
assert_eq!(lcm(0, 7), Some(0));
// Coprime operands above 2^32 overflow the product, which Excel answers with `#NUM!`.
assert_eq!(lcm(1 << 40, (1 << 40) + 1), None);
}
}
+728
View File
@@ -0,0 +1,728 @@
//! Semantic catalog of the DAX functions.
//!
//! The catalog records the documented signature of every function in every
//! <https://dax.guide/functions/> category — arity, parameter kinds, overloads, return type,
//! iterator/volatile behaviour, syntax-sugar relationships, blank handling and host-compatibility
//! flags. It is static metadata: the parser already accepts these calls, and [`crate::validate`]
//! uses the records to reject statically impossible arguments.
//!
//! Documentation conflicts (for example whether `COUNTBLANK` returns 0 when rows exist but no
//! cell is blank) are recorded as [`BlankPolicy::Unspecified`] instead of silently picking one
//! source. See the crate README for the per-function notes.
/// The function family, matching dax.guide's category pages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FunctionCategory {
Aggregation,
DateAndTime,
Filter,
Financial,
Information,
Logical,
MathAndTrig,
Other,
ParentChild,
RelationshipManagement,
Statistical,
TableManipulation,
Text,
TimeIntelligence,
VisualCalculations,
}
impl FunctionCategory {
pub const ALL: [FunctionCategory; 15] = [
FunctionCategory::Aggregation,
FunctionCategory::DateAndTime,
FunctionCategory::Filter,
FunctionCategory::Financial,
FunctionCategory::Information,
FunctionCategory::Logical,
FunctionCategory::MathAndTrig,
FunctionCategory::Other,
FunctionCategory::ParentChild,
FunctionCategory::RelationshipManagement,
FunctionCategory::Statistical,
FunctionCategory::TableManipulation,
FunctionCategory::Text,
FunctionCategory::TimeIntelligence,
FunctionCategory::VisualCalculations,
];
pub const fn name(self) -> &'static str {
match self {
FunctionCategory::Aggregation => "Aggregation",
FunctionCategory::DateAndTime => "Date and Time",
FunctionCategory::Filter => "Filter",
FunctionCategory::Financial => "Financial",
FunctionCategory::Information => "Information",
FunctionCategory::Logical => "Logical",
FunctionCategory::MathAndTrig => "Math and Trig",
FunctionCategory::Other => "Other",
FunctionCategory::ParentChild => "Parent-child",
FunctionCategory::RelationshipManagement => "Relationship management",
FunctionCategory::Statistical => "Statistical",
FunctionCategory::TableManipulation => "Table manipulation",
FunctionCategory::Text => "Text",
FunctionCategory::TimeIntelligence => "Time Intelligence",
FunctionCategory::VisualCalculations => "Visual calculations",
}
}
}
/// What an argument position accepts.
///
/// Only [`ParamKind::Column`] and [`ParamKind::Table`] can be checked without a data model;
/// the remaining kinds are recorded for documentation and future type checking.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ParamKind {
/// A column reference such as `Sales[Amount]` or `[Amount]`.
Column,
/// A table expression such as `Sales`, `FILTER ( ... )` or `{ 1, 2 }`.
Table,
/// A scalar expression evaluated in the iterator's row context.
Expression,
/// A scalar expression evaluated in the caller's context.
Scalar,
/// A logical (Boolean) expression.
Logical,
/// Any expression.
Any,
/// A date/time value.
Date,
/// A text value.
Text,
/// A numeric value.
Number,
/// A Boolean value.
Boolean,
/// A function or lambda reference.
Function,
/// A table or column reference.
Reference,
/// A JSON value.
Json,
/// A value whose type is decided at run time.
Variant,
}
impl ParamKind {
/// Human-readable description used in validation messages.
pub const fn description(self) -> &'static str {
match self {
ParamKind::Column => "a column reference",
ParamKind::Table => "a table expression",
ParamKind::Expression => "an expression",
ParamKind::Scalar => "a scalar expression",
ParamKind::Logical => "a logical expression",
ParamKind::Any => "any expression",
ParamKind::Date => "a date/time expression",
ParamKind::Text => "a text expression",
ParamKind::Number => "a numeric expression",
ParamKind::Boolean => "a Boolean expression",
ParamKind::Function => "a function reference",
ParamKind::Reference => "a table or column reference",
ParamKind::Json => "a JSON value",
ParamKind::Variant => "a value of any type",
}
}
}
/// The documented result type. `Numeric` covers decimal/currency/integer results whose exact
/// type depends on the model, and `Any` covers functions whose result type follows the inputs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ReturnType {
Integer,
Numeric,
Currency,
Decimal,
Any,
Boolean,
DateTime,
String,
Table,
Blank,
Variant,
}
impl ReturnType {
pub const fn name(self) -> &'static str {
match self {
ReturnType::Integer => "Integer",
ReturnType::Numeric => "Numeric",
ReturnType::Currency => "Currency",
ReturnType::Decimal => "Decimal",
ReturnType::Any => "Any",
ReturnType::Boolean => "Boolean",
ReturnType::DateTime => "DateTime",
ReturnType::String => "String",
ReturnType::Table => "Table",
ReturnType::Blank => "Blank",
ReturnType::Variant => "Variant",
}
}
}
/// What the function returns when there is nothing to aggregate.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BlankPolicy {
/// BLANK when the input has no rows or no qualifying value.
BlankWhenEmpty,
/// 0 when rows exist but none match, as Microsoft Learn documents for some functions. The
/// catalog does not currently use this variant: observed engine behaviour and dax.guide
/// disagree with that rule for every function where it was considered.
ZeroWhenRowsButNoMatch,
/// Sources conflict or are silent; callers must not rely on either result.
Unspecified,
}
impl BlankPolicy {
/// Human-readable description used by documentation and tests.
pub const fn description(self) -> &'static str {
match self {
BlankPolicy::BlankWhenEmpty => "BLANK when empty",
BlankPolicy::ZeroWhenRowsButNoMatch => "0 when rows exist but none match",
BlankPolicy::Unspecified => "unspecified",
}
}
}
/// Behaviours that change how a host or optimiser treats the function.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FunctionFlags {
/// The function is an iterator: it evaluates a second argument once per row of a table.
pub iterator: bool,
/// The function may return a different value on every call (`NOW`, `RAND`, ...).
pub volatile: bool,
/// dax.guide marks the function as not recommended.
pub not_recommended: bool,
/// The function is available to Excel's embedded DAX engine.
pub excel_compatible: bool,
/// Microsoft Learn documents DirectQuery restrictions (calculated columns / RLS rules).
pub direct_query_limited: bool,
}
impl FunctionFlags {
pub const fn new(iterator: bool, volatile: bool, not_recommended: bool, excel_compatible: bool, direct_query_limited: bool) -> Self {
FunctionFlags { iterator, volatile, not_recommended, excel_compatible, direct_query_limited }
}
}
/// One argument in a descriptive signature, including whether it may be omitted.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Parameter {
pub name: &'static str,
pub kind: ParamKind,
pub optional: bool,
}
const fn required(name: &'static str, kind: ParamKind) -> Parameter {
Parameter { name, kind, optional: false }
}
const fn optional(name: &'static str, kind: ParamKind) -> Parameter {
Parameter { name, kind, optional: true }
}
/// One exact arity and its parameter kinds. Overloads enumerate every accepted arity, including
/// zero-argument `COUNTROWS ()` and the optional `Variant` argument of `MAXX`/`MINX`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Overload {
pub params: &'static [ParamKind],
/// When true, the last parameter kind repeats for every additional argument.
pub variadic: bool,
}
impl Overload {
pub const fn arity(self) -> usize {
self.params.len()
}
/// Whether this overload accepts exactly `arity` arguments.
pub const fn matches(self, arity: usize) -> bool {
if self.variadic { arity >= self.params.len() } else { arity == self.params.len() }
}
/// The parameter kind at `index`; a variadic overload repeats its last kind.
pub fn kind_at(self, index: usize) -> Option<ParamKind> {
self.params.get(index).copied().or_else(|| if self.variadic { self.params.last().copied() } else { None })
}
}
pub const fn overload(params: &'static [ParamKind]) -> Overload {
Overload { params, variadic: false }
}
pub const fn variadic(params: &'static [ParamKind]) -> Overload {
Overload { params, variadic: true }
}
/// A complete catalog record.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FunctionSpec {
pub name: &'static str,
pub category: FunctionCategory,
pub min_args: usize,
pub max_args: usize,
/// Descriptive signature. Optional markers live here; [`FunctionSpec::overloads`] enumerates
/// the concrete arity/kind combinations.
pub params: &'static [Parameter],
pub overloads: &'static [Overload],
pub return_type: ReturnType,
pub flags: FunctionFlags,
/// The function this one is syntax sugar for, when the semantics are identical.
pub sugar_of: Option<&'static str>,
pub blank_policy: BlankPolicy,
pub description: &'static str,
pub examples: &'static [&'static str],
}
impl FunctionSpec {
/// Whether the function evaluates an expression per row of a table.
pub const fn is_iterator(&self) -> bool {
self.flags.iterator
}
/// The overload accepting exactly `arity` arguments, if any.
pub fn overload_for(&self, arity: usize) -> Option<&Overload> {
self.overloads.iter().find(|overload| overload.matches(arity))
}
}
/// Builds a catalog record with no syntax-sugar link and an unspecified blank policy. Most
/// functions use this; aggregation records spell out the extra fields.
#[allow(clippy::too_many_arguments)]
pub const fn spec(
name: &'static str,
category: FunctionCategory,
min_args: usize,
max_args: usize,
params: &'static [Parameter],
overloads: &'static [Overload],
return_type: ReturnType,
flags: FunctionFlags,
description: &'static str,
examples: &'static [&'static str],
) -> FunctionSpec {
FunctionSpec {
name,
category,
min_args,
max_args,
params,
overloads,
return_type,
flags,
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description,
examples,
}
}
pub const fn standard(iterator: bool) -> FunctionFlags {
FunctionFlags::new(iterator, false, false, true, true)
}
/// All aggregation functions, in the order listed by dax.guide.
pub static AGGREGATION: [FunctionSpec; 22] = [
FunctionSpec {
name: "APPROXIMATEDISTINCTCOUNT",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Integer,
flags: FunctionFlags::new(false, false, false, false, true),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Approximates the number of distinct values in a column. DirectQuery models \
push the aggregation to the source; Import models use HyperLogLog with a \
small error rate. The argument must be a column reference.",
examples: &["APPROXIMATEDISTINCTCOUNT ( Sales[ProductKey] )"],
},
FunctionSpec {
name: "AVERAGE",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Numeric,
flags: standard(false),
sugar_of: Some("AVERAGEX"),
blank_policy: BlankPolicy::Unspecified,
description: "Arithmetic mean of a numeric column, ignoring blanks and including zero. \
Syntax sugar for AVERAGEX. dax.guide returns BLANK when no value qualifies, \
while Microsoft Learn documents 0 when rows exist; the catalog keeps the \
conflict explicit.",
examples: &["AVERAGE ( Sales[Amount] )", "AVERAGE ( Sales[Quantity] )"],
},
FunctionSpec {
name: "AVERAGEA",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Numeric,
flags: FunctionFlags::new(false, false, true, true, true),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "Averages a column, counting TRUE as 1, FALSE as 0 and any text as 0. \
Internally evaluated with AVERAGEX but not pure sugar because of those \
coercions; dax.guide marks it not recommended. Sources disagree on the \
empty/all-blank result.",
examples: &["AVERAGEA ( Customer[LargeFamily] )", "AVERAGEA ( Sales[Flag] )"],
},
FunctionSpec {
name: "AVERAGEX",
category: FunctionCategory::Aggregation,
min_args: 2,
max_args: 2,
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
return_type: ReturnType::Numeric,
flags: standard(true),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Evaluates the expression once per row of the table and returns the mean of \
the non-blank results, including zeros. The expression runs in row context, \
so a measure reference triggers context transition.",
examples: &["AVERAGEX ( Sales, Sales[Quantity] * Sales[Net Price] )", "AVERAGEX ( Customer, [Sales Amount] )"],
},
FunctionSpec {
name: "COUNT",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Integer,
flags: standard(false),
sugar_of: Some("COUNTX"),
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Counts non-blank numbers, dates and strings in a column; empty strings count \
and booleans do not. Syntax sugar for COUNTX.",
examples: &["COUNT ( Customer[Customer Name] )", "COUNT ( Sales[Text] )"],
},
FunctionSpec {
name: "COUNTA",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Integer,
flags: standard(false),
sugar_of: Some("COUNTAX"),
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Counts non-blank values in a column, including booleans (as values, not as \
1/0). Syntax sugar for COUNTAX.",
examples: &["COUNTA ( Customer[Customer Name] )", "COUNTA ( Sales[Flag] )"],
},
FunctionSpec {
name: "COUNTAX",
category: FunctionCategory::Aggregation,
min_args: 2,
max_args: 2,
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
return_type: ReturnType::Integer,
flags: standard(true),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Evaluates the expression per row and counts non-blank results, including \
booleans.",
examples: &["COUNTAX ( Customer, Customer[LargeFamily] )"],
},
FunctionSpec {
name: "COUNTBLANK",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Integer,
flags: standard(false),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "Counts blanks in a column of any type; the empty string counts as blank and \
zero does not. dax.guide says the function never returns 0, while Microsoft \
Learn documents 0 when rows exist but no value is blank.",
examples: &["COUNTBLANK ( Customer[Customer Name] )", "COUNTBLANK ( Sales[Text] )"],
},
FunctionSpec {
name: "COUNTROWS",
category: FunctionCategory::Aggregation,
min_args: 0,
max_args: 1,
params: &[optional("Table", ParamKind::Table)],
overloads: &[overload(&[]), overload(&[ParamKind::Table])],
return_type: ReturnType::Integer,
flags: standard(false),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Counts the rows of a table expression. With no argument it counts the home \
table of the measure or calculated column. Excel's embedded engine accepts \
the one-argument form only.",
examples: &["COUNTROWS ( Sales )", "COUNTROWS ( DISTINCT ( Sales[Region] ) )", "COUNTROWS ( )"],
},
FunctionSpec {
name: "COUNTX",
category: FunctionCategory::Aggregation,
min_args: 2,
max_args: 2,
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
return_type: ReturnType::Integer,
flags: standard(true),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Evaluates the expression per row and counts non-blank results of type number, \
date or string; booleans are not counted (use COUNTAX).",
examples: &["COUNTX ( Customer, DIVIDE ( Customer[Total Children], Customer[Cars Owned] ) )", "COUNTX ( Sales, Sales[Quantity] )"],
},
FunctionSpec {
name: "DISTINCTCOUNT",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Integer,
flags: standard(false),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Counts distinct values in a column of any type. BLANK is one distinct value; \
totals are not additive. Equivalent to COUNTROWS ( DISTINCT ( table[column] ) ).",
examples: &["DISTINCTCOUNT ( Store[Area Manager] )", "DISTINCTCOUNT ( Sales[Region] )"],
},
FunctionSpec {
name: "DISTINCTCOUNTNOBLANK",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Integer,
flags: FunctionFlags::new(false, false, false, false, true),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "Counts distinct values in a column, excluding BLANK — DISTINCTCOUNT counts \
BLANK, so this is not pure sugar for it. Not available to Excel's embedded \
engine.",
examples: &["DISTINCTCOUNTNOBLANK ( Store[Area Manager] )"],
},
FunctionSpec {
name: "MAX",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 2,
params: &[required("ColumnNameOrScalar1", ParamKind::Any), optional("Scalar2", ParamKind::Scalar)],
overloads: &[overload(&[ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Scalar])],
return_type: ReturnType::Any,
flags: standard(false),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "With one argument, the largest non-blank value of a column (the same result \
MAXX gives over the column); text compares alphabetically and logical values are unsupported. With \
two arguments, the larger scalar, where BLANK is significant per dax.guide \
but treated as zero by Microsoft Learn.",
examples: &["MAX ( Sales[Net Price] )", "MAX ( 10000, [Sales Amount] )", "MAX ( 3, 5 )"],
},
FunctionSpec {
name: "MAXA",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Any,
flags: standard(false),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "Largest value of a column, counting TRUE as 1 and FALSE as 0 instead of \
ignoring logical values. Internally MAXX. Sources disagree on the empty \
result; text is not rankable.",
examples: &["MAXA ( Customer[LargeFamily] )", "MAXA ( Sales[Flag] )"],
},
FunctionSpec {
name: "MAXX",
category: FunctionCategory::Aggregation,
min_args: 2,
max_args: 3,
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), optional("Variant", ParamKind::Logical)],
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression]), overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Logical])],
return_type: ReturnType::Any,
flags: standard(true),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "Evaluates the expression per row and returns the largest value, skipping \
blanks and ignoring logical values. Mixed-type expressions consider numbers \
only unless Variant is TRUE, which compares per ORDER BY DESC.",
examples: &["MAXX ( Customer, 1 * Customer[LargeFamily] )", "MAXX ( Sales, Sales[Amount], TRUE )"],
},
FunctionSpec {
name: "MIN",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 2,
params: &[required("ColumnNameOrScalar1", ParamKind::Any), optional("Scalar2", ParamKind::Scalar)],
overloads: &[overload(&[ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Scalar])],
return_type: ReturnType::Any,
flags: standard(false),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "With one argument, the smallest non-blank value of a column (the same result \
MINX gives over the column); text compares alphabetically and logical values are unsupported. With \
two arguments, the smaller scalar, where BLANK is significant per dax.guide \
but treated as zero by Microsoft Learn.",
examples: &["MIN ( Sales[Net Price] )", "MIN ( 5000000, [Sales Amount] )", "MIN ( 3, 5 )"],
},
FunctionSpec {
name: "MINA",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Any,
flags: standard(false),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "Smallest value of a column, counting TRUE as 1 and FALSE as 0 instead of \
ignoring logical values. Internally MINX. Sources disagree on the empty \
result.",
examples: &["MINA ( Customer[LargeFamily] )", "MINA ( Sales[Flag] )"],
},
FunctionSpec {
name: "MINX",
category: FunctionCategory::Aggregation,
min_args: 2,
max_args: 3,
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), optional("Variant", ParamKind::Logical)],
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression]), overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Logical])],
return_type: ReturnType::Any,
flags: standard(true),
sugar_of: None,
blank_policy: BlankPolicy::Unspecified,
description: "Evaluates the expression per row and returns the smallest value, skipping \
blanks and ignoring logical values. Mixed-type expressions consider numbers \
only unless Variant is TRUE, which compares per ORDER BY ASC.",
examples: &["MINX ( Customer, 1 * Customer[NoCars] )", "MINX ( Sales, Sales[Amount], FALSE )"],
},
FunctionSpec {
name: "PRODUCT",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Decimal,
flags: standard(false),
sugar_of: Some("PRODUCTX"),
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Multiplies the numbers in a column, ignoring blanks, logical values and text. \
Syntax sugar for PRODUCTX.",
examples: &["PRODUCT ( Sales[Quantity] )"],
},
FunctionSpec {
name: "PRODUCTX",
category: FunctionCategory::Aggregation,
min_args: 2,
max_args: 2,
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
return_type: ReturnType::Decimal,
flags: standard(true),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Evaluates the expression per row and multiplies the non-blank numeric \
results; blanks, logical values and text are ignored, unlike the `*` \
operator.",
examples: &["PRODUCTX ( Rates, 1 + Rates[InflationRate] )", "PRODUCTX ( Sales, Sales[Quantity] )"],
},
FunctionSpec {
name: "SUM",
category: FunctionCategory::Aggregation,
min_args: 1,
max_args: 1,
params: &[required("ColumnName", ParamKind::Column)],
overloads: &[overload(&[ParamKind::Column])],
return_type: ReturnType::Numeric,
flags: standard(false),
sugar_of: Some("SUMX"),
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Adds the numbers in a column, ignoring blanks, logical values and text. \
Syntax sugar for SUMX. dax.guide says the result type follows the column, \
while Microsoft Learn documents a decimal number.",
examples: &["SUM ( Sales[Amount] )", "SUM ( Sales[Quantity] )"],
},
FunctionSpec {
name: "SUMX",
category: FunctionCategory::Aggregation,
min_args: 2,
max_args: 2,
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
return_type: ReturnType::Numeric,
flags: standard(true),
sugar_of: None,
blank_policy: BlankPolicy::BlankWhenEmpty,
description: "Evaluates the expression once per row of the table and sums the numeric \
results; blanks, logical values and text are ignored. The expression runs \
in row context.",
examples: &[
"SUMX ( Sales, Sales[Quantity] * Sales[Net Price] )",
"SUMX ( FILTER ( InternetSales, InternetSales[SalesTerritoryID] = 5 ), [Freight] )",
],
},
];
pub mod date_time;
pub mod filter;
pub mod financial;
pub mod information;
pub mod logical;
pub mod math_trig;
pub mod other;
pub mod parent_child;
pub mod relationships;
pub mod statistical;
pub mod table_manipulation;
pub mod text;
pub mod time_intelligence;
pub mod visual_calculations;
/// Every function from every category, in dax.guide category order.
static CATALOG: std::sync::LazyLock<Vec<FunctionSpec>> = std::sync::LazyLock::new(|| {
let mut all = Vec::with_capacity(600);
all.extend_from_slice(&AGGREGATION);
all.extend_from_slice(date_time::FUNCTIONS);
all.extend_from_slice(filter::FUNCTIONS);
all.extend_from_slice(financial::FUNCTIONS);
all.extend_from_slice(information::FUNCTIONS);
all.extend_from_slice(logical::FUNCTIONS);
all.extend_from_slice(math_trig::FUNCTIONS);
all.extend_from_slice(other::FUNCTIONS);
all.extend_from_slice(parent_child::FUNCTIONS);
all.extend_from_slice(relationships::FUNCTIONS);
all.extend_from_slice(statistical::FUNCTIONS);
all.extend_from_slice(table_manipulation::FUNCTIONS);
all.extend_from_slice(text::FUNCTIONS);
all.extend_from_slice(time_intelligence::FUNCTIONS);
all.extend_from_slice(visual_calculations::FUNCTIONS);
all
});
/// Every catalogued function.
pub fn catalog() -> &'static [FunctionSpec] {
&CATALOG
}
/// Looks a function up by name, ignoring ASCII case.
pub fn lookup(name: &str) -> Option<&'static FunctionSpec> {
CATALOG.iter().find(|spec| spec.name.eq_ignore_ascii_case(name))
}
+366
View File
@@ -0,0 +1,366 @@
//! Date and time functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
use FunctionCategory::DateAndTime;
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"CALENDAR",
DateAndTime,
2,
2,
&[required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date)],
&[overload(&[ParamKind::Date, ParamKind::Date])],
ReturnType::Table,
standard(false),
"CALENDAR ( <StartDate>, <EndDate> ) returns a single-column table named Date with every \
day from StartDate to EndDate, both included. Dates are stored as numbers, so integer \
bounds such as CALENDAR ( 1, 100 ) are accepted; a date table should cover whole years \
for time-intelligence compatibility.",
&["CALENDAR ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )", "CALENDAR ( DATE ( 2023, 7, 1 ), DATE ( 2024, 6, 30 ) )"],
),
spec(
"CALENDARAUTO",
DateAndTime,
0,
1,
&[optional("FiscalYearEndMonth", ParamKind::Number)],
&[overload(&[]), overload(&[ParamKind::Number])],
ReturnType::Table,
standard(false),
"CALENDARAUTO ( [<FiscalYearEndMonth>] ) scans the imported date columns and returns a \
contiguous Date table covering whole fiscal years. FiscalYearEndMonth is 1-12 and \
defaults to 12 (December); calculated tables and calculated columns are ignored, and \
the model must contain at least one imported datetime column or the call fails.",
&["CALENDARAUTO ()", "CALENDARAUTO ( 6 )"],
),
spec(
"DATE",
DateAndTime,
3,
3,
&[required("Year", ParamKind::Number), required("Month", ParamKind::Number), required("Day", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
ReturnType::DateTime,
standard(false),
"DATE ( <Year>, <Month>, <Day> ) builds a DateTime from numeric parts. Years 0-99 add \
1900 (DATE ( 98, 1, 2 ) is 1998-01-02) while years below -1800 or above 9999 raise an \
error; month and day overflow roll into neighbouring months and days (DATE ( 2024, 13, \
1 ) is 2025-01-01).",
&["DATE ( 2024, 1, 1 )", "DATE ( 2024, 13, 1 )", "DATE ( YEAR ( Sales[Order Date] ), 1, 1 )"],
),
spec(
"DATEDIFF",
DateAndTime,
3,
3,
&[required("Date1", ParamKind::Date), required("Date2", ParamKind::Date), required("Interval", ParamKind::Any)],
&[overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Any])],
ReturnType::Integer,
standard(false),
"DATEDIFF ( <Date1>, <Date2>, <Interval> ) counts the Interval boundaries crossed \
between two dates, positively when Date2 is later and negatively otherwise. Interval is \
an unquoted keyword: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or YEAR.",
&["DATEDIFF ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), DAY )", "DATEDIFF ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), MONTH )"],
),
spec(
"DATEVALUE",
DateAndTime,
1,
1,
&[required("DateText", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::DateTime,
standard(false),
"DATEVALUE ( <DateText> ) converts a text date to a DateTime using the locale of the \
model, so \"1/8/2009\" may mean January 8 or August 1. A missing year is taken from the \
current year and any time portion is ignored.",
&["DATEVALUE ( \"2024-01-01\" )", "DATEVALUE ( \"1/8/2009\" )"],
),
spec(
"DAY",
DateAndTime,
1,
1,
&[required("Date", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Integer,
standard(false),
"DAY ( <Date> ) returns the day of the month as an integer from 1 to 31. A text argument \
is converted with the same rules as DATEVALUE, so the locale of the model decides how \
the text is read.",
&["DAY ( DATE ( 2024, 1, 15 ) )", "DAY ( Sales[Order Date] )"],
),
spec(
"EDATE",
DateAndTime,
2,
2,
&[required("StartDate", ParamKind::Date), required("Months", ParamKind::Number)],
&[overload(&[ParamKind::Date, ParamKind::Number])],
ReturnType::DateTime,
standard(false),
"EDATE ( <StartDate>, <Months> ) shifts a date by the given number of months, keeping the \
day of the month and clamping to the end of shorter months (2024-01-31 plus one month \
is 2024-02-29). Unlike EOMONTH it does not move to the end of the month.",
&["EDATE ( DATE ( 2024, 1, 31 ), 1 )", "EDATE ( Sales[Order Date], -3 )"],
),
spec(
"EOMONTH",
DateAndTime,
2,
2,
&[required("StartDate", ParamKind::Date), required("Months", ParamKind::Number)],
&[overload(&[ParamKind::Date, ParamKind::Number])],
ReturnType::DateTime,
standard(false),
"EOMONTH ( <StartDate>, <Months> ) returns the last day of the month that is Months \
before or after StartDate; 0 gives the end of the current month. There is no SOMONTH, so \
the start of a month is EOMONTH ( <date>, -1 ) + 1.",
&["EOMONTH ( DATE ( 2024, 1, 15 ), 0 )", "EOMONTH ( Sales[Order Date], 1 )"],
),
spec(
"HOUR",
DateAndTime,
1,
1,
&[required("Datetime", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Integer,
standard(false),
"HOUR ( <Datetime> ) gives the hour as an integer from 0 to 23. A string that holds only \
a time, such as \"16:48:00\", is accepted and parsed using the client computer's locale \
and time settings.",
&["HOUR ( TIME ( 16, 48, 23 ) )", "HOUR ( Sales[Order Time] )"],
),
spec(
"MINUTE",
DateAndTime,
1,
1,
&[required("Datetime", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Integer,
standard(false),
"MINUTE ( <Datetime> ) gives the minute as an integer from 0 to 59. A string that holds \
only a time, such as \"16:48:00\", is accepted and parsed using the client computer's \
locale and time settings.",
&["MINUTE ( TIME ( 16, 48, 23 ) )", "MINUTE ( Sales[Order Time] )"],
),
spec(
"MONTH",
DateAndTime,
1,
1,
&[required("Date", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Integer,
standard(false),
"MONTH ( <Date> ) gives 1 for January through 12 for December. Text arguments are read \
with the same rules as DATEVALUE.",
&["MONTH ( DATE ( 2024, 1, 15 ) )", "MONTH ( Sales[Order Date] )"],
),
spec(
"NETWORKDAYS",
DateAndTime,
2,
4,
&[
required("start_date", ParamKind::Date),
required("end_date", ParamKind::Date),
optional("weekend", ParamKind::Number),
optional("holidays", ParamKind::Table),
],
&[
overload(&[ParamKind::Date, ParamKind::Date]),
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number]),
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Table]),
],
ReturnType::Integer,
FunctionFlags::new(false, false, false, false, true),
"NETWORKDAYS ( <start_date>, <end_date> [, <weekend>] [, <holidays>] ) counts whole \
workdays between two dates, both included, skipping weekends and holidays. The weekend \
code defaults to 1 (Saturday and Sunday), accepts 2-7 for other pairs and 11-17 for a \
single day; holidays is a single-column table of dates. Not available in Excel's DAX \
engine.",
&[
"NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ) )",
"NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), 1, { DATE ( 2024, 1, 15 ) } )",
],
),
spec(
"NOW",
DateAndTime,
0,
0,
&[],
&[overload(&[])],
ReturnType::DateTime,
FunctionFlags::new(false, true, false, true, true),
"Date and time at the moment of evaluation. Volatile: it is evaluated once per query and \
moves only when the model or the containing calculated column is refreshed, not \
continuously.",
&["NOW ()", "YEAR ( NOW () )"],
),
spec(
"QUARTER",
DateAndTime,
1,
1,
&[required("Date", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Integer,
standard(false),
"QUARTER ( <Date> ) gives the calendar quarter number, 1 for January-March through 4 for \
October-December; fiscal periods are not followed. Text arguments are read with the \
same rules as DATEVALUE.",
&["QUARTER ( DATE ( 2024, 5, 15 ) )", "QUARTER ( Sales[Order Date] )"],
),
spec(
"SECOND",
DateAndTime,
1,
1,
&[required("Datetime", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Integer,
standard(false),
"SECOND ( <Datetime> ) gives the second as an integer from 0 to 59. A string that holds \
only a time, such as \"16:48:23\", is accepted and parsed using the client computer's \
locale and time settings.",
&["SECOND ( TIME ( 16, 48, 23 ) )", "SECOND ( Sales[Order Time] )"],
),
spec(
"TIME",
DateAndTime,
3,
3,
&[required("Hour", ParamKind::Number), required("Minute", ParamKind::Number), required("Second", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
ReturnType::DateTime,
standard(false),
"TIME ( <Hour>, <Minute>, <Second> ) builds a time on the 1899-12-30 epoch. 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), and each argument is limited to 32,767.",
&["TIME ( 16, 48, 23 )", "TIME ( 10, 90, 0 )"],
),
spec(
"TIMEVALUE",
DateAndTime,
1,
1,
&[required("TimeText", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::DateTime,
standard(false),
"TIMEVALUE ( <TimeText> ) converts a text time to a DateTime, ignoring any date portion \
of the string. Parsing uses the client computer's locale, date and time settings, so the \
same text can fail or mean a different time on another machine.",
&["TIMEVALUE ( \"16:48:23\" )", "TIMEVALUE ( \"4:48:47 PM\" )"],
),
spec(
"TODAY",
DateAndTime,
0,
0,
&[],
&[overload(&[])],
ReturnType::DateTime,
FunctionFlags::new(false, true, false, true, true),
"TODAY () returns the current date at 12:00:00 AM. Volatile: it is evaluated once per \
query and only changes when the model or the containing calculated column is refreshed, \
not continuously.",
&["TODAY ()", "TODAY () - Sales[Order Date]"],
),
spec(
"UTCNOW",
DateAndTime,
0,
0,
&[],
&[overload(&[])],
ReturnType::DateTime,
FunctionFlags::new(false, true, false, true, true),
"UTCNOW () gives the date and time at the moment of evaluation, expressed in Coordinated \
Universal Time. Volatile: it is evaluated once per query. The Power BI Service always \
runs on UTC and applies no daylight saving, so NOW and UTCNOW agree there.",
&["UTCNOW ()", "NOW () - UTCNOW ()"],
),
spec(
"UTCTODAY",
DateAndTime,
0,
0,
&[],
&[overload(&[])],
ReturnType::DateTime,
FunctionFlags::new(false, true, false, true, true),
"UTCTODAY () returns the current date at 12:00:00 AM in Coordinated Universal Time. \
Volatile: it is evaluated once per query and only changes when the model is refreshed.",
&["UTCTODAY ()", "TODAY () - UTCTODAY ()"],
),
spec(
"WEEKDAY",
DateAndTime,
1,
2,
&[required("Date", ParamKind::Date), optional("ReturnType", ParamKind::Number)],
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Number])],
ReturnType::Integer,
standard(false),
"WEEKDAY ( <Date> [, <ReturnType>] ) returns the day of the week. ReturnType 1 (default) \
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. A text \
argument is converted with the same rules as DATEVALUE.",
&["WEEKDAY ( DATE ( 2024, 1, 1 ) )", "WEEKDAY ( Sales[Order Date], 2 )"],
),
spec(
"WEEKNUM",
DateAndTime,
1,
2,
&[required("Date", ParamKind::Date), optional("ReturnType", ParamKind::Number)],
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Number])],
ReturnType::Integer,
standard(false),
"WEEKNUM ( <Date> [, <ReturnType>] ) gives the week number within the year. The documented \
codes are 1 (default), 2, 11-17 and 21: 1, 2 and 11-17 use system 1, where the week \
containing January 1 is week 1 (each code picks the first day of the week: 1 Sunday, 2 \
Monday, 11 Monday, 12 Tuesday, ... 17 Sunday), and 21 uses ISO 8601 system 2, where the \
week containing the first Thursday is week 1. Codes 3-10 are not valid. Text arguments \
are read with the same rules as DATEVALUE.",
&["WEEKNUM ( DATE ( 2024, 1, 15 ) )", "WEEKNUM ( Sales[Order Date], 21 )"],
),
spec(
"YEAR",
DateAndTime,
1,
1,
&[required("Date", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Integer,
standard(false),
"YEAR ( <Date> ) gives the calendar year as a four-digit integer between 1900 and 9999. \
Text arguments are read with the same rules as DATEVALUE.",
&["YEAR ( DATE ( 2024, 1, 1 ) )", "YEAR ( Sales[Order Date] )"],
),
spec(
"YEARFRAC",
DateAndTime,
2,
3,
&[required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date), optional("Basis", ParamKind::Number)],
&[overload(&[ParamKind::Date, ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"YEARFRAC ( <StartDate>, <EndDate> [, <Basis>] ) returns the fraction of a year between \
two dates. Basis selects the day-count convention: 0 (default) US 30/360, 1 \
actual/actual, 2 actual/360, 3 actual/365 and 4 European 30/360. Because of a known bug \
in age calculations, dax.guide suggests INT arithmetic instead.",
&["YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )", "YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), 1 )"],
),
];
+561
View File
@@ -0,0 +1,561 @@
//! Filter functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! This category covers table expressions that inspect or remove filter context (`ALL`,
//! `ALLSELECTED`, ...), the two functions that build a filter context (`CALCULATE`,
//! `CALCULATETABLE`), and the window/apply clauses (`INDEX`, `OFFSET`, `WINDOW`, `ORDERBY`,
//! `PARTITIONBY`, `MATCHBY`) that are only meaningful inside one of those table expressions.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
/// Functions whose original implementation shipped in Excel's embedded engine. The argument
/// order and semantics are shared with Excel 2016 and later.
const EXCEL: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
/// Engine features that Power BI uses internally for composite models and window functions.
/// Excel's embedded engine rejects them, and the DirectQuery notes still apply.
const INTERNAL: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
/// `FILTER` is an iterator: it evaluates its predicate once per row.
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"ALL",
FunctionCategory::Filter,
0,
usize::MAX,
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
ReturnType::Table,
EXCEL,
"Returns a table ignoring any filters on it, or every value of a column ignoring the \
filters on that column. As a table expression it materialises all rows (or all distinct \
values of one or more columns). Without arguments it works only inside \
CALCULATE/CALCULATETABLE and clears the whole filter context.",
&["ALL ( Sales )", "ALL ( Sales[Region] )", "ALL ( Sales, Sales[Region], Sales[Country] )", "ALL ( )"],
),
spec(
"ALLCROSSFILTERED",
FunctionCategory::Filter,
1,
1,
&[required("TableName", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
EXCEL,
"Removes, as a CALCULATE modifier only, every filter on a table and on the tables that \
cross-filter it through weak or bidirectional relationships. Unlike ALL it never returns \
a materialised table, so it cannot be used as a table expression.",
&["ALLCROSSFILTERED ( Sales )", "ALLCROSSFILTERED ( 'Product' )"],
),
spec(
"ALLEXCEPT",
FunctionCategory::Filter,
2,
usize::MAX,
&[required("TableName", ParamKind::Table), required("ColumnName", ParamKind::Column), optional("ColumnName", ParamKind::Column)],
&[variadic(&[ParamKind::Table, ParamKind::Column])],
ReturnType::Table,
EXCEL,
"Removes all filters from a table except those on the listed columns. As a CALCULATE \
modifier it keeps only the named column filters; as a table expression it materialises \
the unique combinations of the table's remaining columns.",
&["ALLEXCEPT ( Sales, Sales[Region] )", "ALLEXCEPT ( 'Product', 'Product'[Color], 'Product'[Brand] )"],
),
spec(
"ALLNOBLANKROW",
FunctionCategory::Filter,
1,
usize::MAX,
&[required("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
ReturnType::Table,
EXCEL,
"Like ALL, removes the filters on a table or on the listed columns, but always excludes \
the blank row that the engine adds for an invalid relationship. Real blank values stored \
in the columns are kept in the result.",
&["ALLNOBLANKROW ( Customer )", "ALLNOBLANKROW ( Customer[Country], Customer[City] )"],
),
spec(
"ALLSELECTED",
FunctionCategory::Filter,
0,
usize::MAX,
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
ReturnType::Table,
EXCEL,
"Restores the filters that came from outside the query while ignoring the filters applied \
inside it, so the result reflects the outer shadow filter context. As a table expression \
it needs at least one argument; without arguments it is only a CALCULATE modifier.",
&["ALLSELECTED ( Sales )", "ALLSELECTED ( Sales[Region] )", "ALLSELECTED ( )"],
),
spec(
"ALLSELECTEDAPPLY",
FunctionCategory::Filter,
1,
1,
&[required("TableExpression", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
INTERNAL,
"Marks a table expression supplied to GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE so that it \
starts hidden from the filter context and only becomes active when ALLSELECTED runs \
inside CALCULATE. Used internally by Power BI composite models.",
&["ALLSELECTEDAPPLY ( VALUES ( Product[Color] ) )"],
),
spec(
"ALLSELECTEDREMOVE",
FunctionCategory::Filter,
1,
usize::MAX,
&[required("TableExpression", ParamKind::Table), optional("Column", ParamKind::Column)],
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Column])],
ReturnType::Table,
INTERNAL,
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, hides the listed columns of a table \
expression from a later ALLSELECTED so they no longer participate in the restored filter \
context. With no column argument every column of the expression is hidden.",
&["ALLSELECTEDREMOVE ( VALUES ( Product[Color] ) )", "ALLSELECTEDREMOVE ( VALUES ( Product[Color] ), Product[Color] )"],
),
spec(
"ALWAYSAPPLY",
FunctionCategory::Filter,
1,
1,
&[required("TableExpression", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
INTERNAL,
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, forces a filter table to influence the \
measures even if the current filter context is unchanged, for example when the table is \
empty. Used internally by Power BI composite models.",
&["ALWAYSAPPLY ( FILTER ( VALUES ( Product[Color] ), FALSE ) )"],
),
spec(
"CALCULATE",
FunctionCategory::Filter,
1,
usize::MAX,
&[required("Expression", ParamKind::Expression), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression]), variadic(&[ParamKind::Expression, ParamKind::Any])],
ReturnType::Any,
EXCEL,
"Evaluates an expression in a filter context modified by its filter arguments: table \
expressions replace the filters on their columns, boolean predicates are wrapped in \
FILTER over ALL, and context transition turns any row context into an equivalent filter \
context. Returns the scalar result of the expression.",
&["CALCULATE ( SUM ( Sales[Amount] ), Sales[Region] = \"East\" )", "CALCULATE ( [Sales Amount], ALL ( Product ) )"],
),
spec(
"CALCULATETABLE",
FunctionCategory::Filter,
1,
usize::MAX,
&[required("Table", ParamKind::Table), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Any])],
ReturnType::Table,
EXCEL,
"Runs a table expression under the filter context built by its filter arguments, with \
the same filter semantics and context transition as CALCULATE but returning a table \
instead of a scalar.",
&["CALCULATETABLE ( VALUES ( Product[Color] ), Product[Brand] = \"GridCraft\" )"],
),
spec(
"DEPENDON",
FunctionCategory::Filter,
2,
usize::MAX,
&[required("TableExpression", ParamKind::Table), required("ColumnName", ParamKind::Column), optional("ColumnName", ParamKind::Column)],
&[variadic(&[ParamKind::Table, ParamKind::Column])],
ReturnType::Table,
INTERNAL,
"Anchors a table expression to outer columns: its first columns are matched, in order, \
against the current values of the listed outer columns, acting as an inner join and \
hiding the matched columns from the result. Used internally by Power BI composite \
models.",
&["DEPENDON ( Sales, Sales[OrderDate] )", "DEPENDON ( FILTER ( Sales, Sales[Amount] > 0 ), Sales[OrderDate] )"],
),
spec(
"FILTER",
FunctionCategory::Filter,
2,
2,
&[required("Table", ParamKind::Table), required("FilterExpression", ParamKind::Logical)],
&[overload(&[ParamKind::Table, ParamKind::Logical])],
ReturnType::Table,
ITERATOR,
"Returns the rows of a table for which the predicate is TRUE. The predicate runs in a row \
context, so it can read the current row's columns; context transition applies when it \
calls a measure, and BLANK evaluates as FALSE. Filter context is preserved, not replaced.",
&["FILTER ( Sales, Sales[Amount] > 0 )", "FILTER ( ALL ( Sales ), Sales[Region] = \"East\" )"],
),
spec(
"FILTERCLUSTER",
FunctionCategory::Filter,
4,
usize::MAX,
&[
required("GroupBy_ColumnName", ParamKind::Column),
required("FilterTable", ParamKind::Table),
required("Separator", ParamKind::Text),
required("TableScan", ParamKind::Table),
],
&[variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Text, ParamKind::Any])],
ReturnType::Table,
INTERNAL,
"Internal helper for GROUPCROSSAPPLY and GROUPCROSSAPPLYTABLE that assembles the \
correlated join over a set of groups: group-by columns, filter tables and table scans \
are combined with autoexist semantics, and the literal separator only marks where the \
table scans begin. Used internally by Power BI composite models.",
&["FILTERCLUSTER ( Product[Category], ALL ( Product ), \"\", ALL ( Sales ) )"],
),
spec(
"GROUPCROSSAPPLY",
FunctionCategory::Filter,
2,
usize::MAX,
&[
required("GroupBy_ColumnName", ParamKind::Column),
required("FilterTable", ParamKind::Table),
optional("Name", ParamKind::Text),
optional("Expression", ParamKind::Any),
],
&[overload(&[ParamKind::Column, ParamKind::Table]), variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Any])],
ReturnType::Table,
INTERNAL,
"Aggregates by the group-by columns across cross-joined filter tables, with no implicit \
autoexist. Each name/expression pair adds a column, and rows whose expressions are all \
blank are dropped. Used internally by Power BI composite models.",
&["GROUPCROSSAPPLY ( 'Date'[Year], ALL ( 'Date' ) )", "GROUPCROSSAPPLY ( 'Date'[Year], ALL ( 'Date' ), \"Sales\", [Sales Amount] )"],
),
spec(
"GROUPCROSSAPPLYTABLE",
FunctionCategory::Filter,
2,
usize::MAX,
&[
required("GroupBy_ColumnName", ParamKind::Column),
required("FilterTable", ParamKind::Table),
optional("Name", ParamKind::Text),
optional("TableExpression", ParamKind::Table),
],
&[overload(&[ParamKind::Column, ParamKind::Table]), variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Any])],
ReturnType::Table,
INTERNAL,
"Like GROUPCROSSAPPLY, but the trailing name/table-expression pairs add whole tables \
evaluated under the filter tables' context instead of scalar expressions. Used \
internally by Power BI composite models.",
&["GROUPCROSSAPPLYTABLE ( 'Date'[Year], ALL ( 'Date' ), \"Colors\", VALUES ( 'Product'[Color] ) )"],
),
spec(
"INDEX",
FunctionCategory::Filter,
1,
7,
&[
required("Position", ParamKind::Number),
optional("Relation", ParamKind::Table),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("PartitionBy", ParamKind::Any),
optional("MatchBy", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Table]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Table,
INTERNAL,
"Returns, as a one-row table, the row at an absolute position (1-based, negative counts \
from the end) within each partition of the relation, sorted by the ORDERBY clause. An \
out-of-range or zero position yields an empty table; the relation defaults to \
ALLSELECTED over the ordering and partitioning columns.",
&[
"INDEX ( 1, Sales, ORDERBY ( Sales[OrderDate] ) )",
"INDEX ( -1, ALLSELECTED ( Sales ) )",
"INDEX ( 1, Sales, ORDERBY ( Sales[OrderDate] ), KEEP, PARTITIONBY ( Sales[Region] ) )",
],
),
spec(
"KEEPFILTERS",
FunctionCategory::Filter,
1,
1,
&[required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Expression])],
ReturnType::Any,
EXCEL,
"Filter modifier that makes its argument intersect the existing filter context instead of \
replacing it, so a conflicting existing filter is kept. Applies to a CALCULATE or \
CALCULATETABLE filter argument and also preserves the filter context during context \
transition in an iterator.",
&["KEEPFILTERS ( Product[Color] = \"Red\" )", "KEEPFILTERS ( VALUES ( Product[Color] ) )"],
),
spec(
"LOOKUP",
FunctionCategory::Filter,
3,
usize::MAX,
&[
required("Result_ColumnOrExpression", ParamKind::Any),
required("Search_Column", ParamKind::Column),
required("Search_Value", ParamKind::Any),
optional("Search_Column", ParamKind::Column),
optional("Search_Value", ParamKind::Any),
optional("AssociatedColumnsBehavior", ParamKind::Text),
],
&[variadic(&[ParamKind::Any, ParamKind::Column, ParamKind::Any])],
ReturnType::Any,
INTERNAL,
"Searches the cells identified by the search column/value pairs and returns a column value \
or an expression evaluated over those cells; filters on columns not listed stay applied. \
Only one cell may match, and the optional behaviour argument selects Explicit or \
Inferred handling of associated columns.",
&["LOOKUP ( [Sales Amount], 'Date'[Year], 2018 )", "LOOKUP ( [Sales Amount], 'Date'[Year], 2018, \"Inferred\" )"],
),
spec(
"LOOKUPVALUE",
FunctionCategory::Filter,
3,
usize::MAX,
&[
required("Result_ColumnName", ParamKind::Column),
required("Search_ColumnName", ParamKind::Column),
required("Search_Value", ParamKind::Any),
optional("Search_ColumnName", ParamKind::Column),
optional("Search_Value", ParamKind::Any),
optional("Alternate_Result", ParamKind::Any),
],
&[variadic(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])],
ReturnType::Any,
EXCEL,
"Returns the result column value from the row where every search column/value pair \
matches, ignoring the current filter context. With no match it returns BLANK or the \
alternate result; identical values in several matching rows return that value, while \
different values return the alternate result or an error.",
&["LOOKUPVALUE ( Product[Color], Product[ProductKey], 1 )", "LOOKUPVALUE ( Product[Color], Product[ProductKey], 1, \"Unknown\" )"],
),
spec(
"LOOKUPWITHTOTALS",
FunctionCategory::Filter,
3,
usize::MAX,
&[
required("Result_ColumnOrExpression", ParamKind::Any),
required("Search_Column", ParamKind::Column),
required("Search_Value", ParamKind::Any),
optional("Search_Column", ParamKind::Column),
optional("Search_Value", ParamKind::Any),
],
&[variadic(&[ParamKind::Any, ParamKind::Column, ParamKind::Any])],
ReturnType::Any,
INTERNAL,
"Searches the cells identified by the search column/value pairs, like LOOKUP, but resets \
the non-specified columns to their grand total instead of keeping the current filters. \
Equivalent to COLLAPSEALL around LOOKUP.",
&["LOOKUPWITHTOTALS ( [Sales Amount], [Year], 2018 )"],
),
spec(
"MATCHBY",
FunctionCategory::Filter,
0,
usize::MAX,
&[optional("MatchBy_ColumnName", ParamKind::Column)],
&[overload(&[]), variadic(&[ParamKind::Column])],
ReturnType::Any,
INTERNAL,
"Declares the columns that identify the current row for a window function such as INDEX, \
OFFSET or WINDOW. It is a clause, not a value: it can only appear inside a window \
function and does not change the filter context by itself.",
&["MATCHBY ( Sales[OrderKey] )", "MATCHBY ( )"],
),
spec(
"NONFILTER",
FunctionCategory::Filter,
1,
1,
&[required("TableExpression", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
INTERNAL,
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, keeps a table expression out of the filter \
context permanently, even when its columns carry lineage, as if they were extension \
columns. Used internally by Power BI composite models.",
&["NONFILTER ( VALUES ( Product[Color] ) )"],
),
spec(
"OFFSET",
FunctionCategory::Filter,
1,
7,
&[
required("Delta", ParamKind::Number),
optional("Relation", ParamKind::Table),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("PartitionBy", ParamKind::Any),
optional("MatchBy", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Table]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Table,
INTERNAL,
"Returns the row that is a number of rows before or after the current row within each \
partition of the relation, ordered by the ORDERBY clause. The result is a one-row table; \
a delta moving outside the partition yields an empty table.",
&["OFFSET ( -1, Sales, ORDERBY ( Sales[OrderDate] ) )", "OFFSET ( 1, Sales )"],
),
spec(
"ORDERBY",
FunctionCategory::Filter,
0,
usize::MAX,
&[optional("OrderBy_Expression", ParamKind::Any), optional("OrderBy_Direction", ParamKind::Any)],
&[overload(&[]), variadic(&[ParamKind::Any])],
ReturnType::Any,
INTERNAL,
"Declares the sort expressions and directions (ASC or DESC, optionally with BLANKS FIRST \
or BLANKS LAST) used by a window function such as INDEX, OFFSET or WINDOW. It is a \
clause rather than a value and cannot be evaluated on its own.",
&["ORDERBY ( Sales[Amount], DESC )", "ORDERBY ( Sales[OrderDate], ASC )", "ORDERBY ( )"],
),
spec(
"PARTITIONBY",
FunctionCategory::Filter,
0,
usize::MAX,
&[optional("PartitionBy_ColumnName", ParamKind::Column)],
&[overload(&[]), variadic(&[ParamKind::Column])],
ReturnType::Any,
INTERNAL,
"Declares the model columns that partition the relation of a window function such as \
INDEX, OFFSET or WINDOW. It is a clause rather than a value, and the columns must have a \
valid data lineage.",
&["PARTITIONBY ( Sales[Region] )", "PARTITIONBY ( )"],
),
spec(
"REMOVEFILTERS",
FunctionCategory::Filter,
0,
usize::MAX,
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
ReturnType::Any,
EXCEL,
"Alias for ALL with the same filter-removal semantics: it clears the filters on the named \
table or columns, or every filter when called without arguments. It is only valid as a \
CALCULATE or CALCULATETABLE modifier and never returns a table.",
&["REMOVEFILTERS ( Sales )", "REMOVEFILTERS ( Sales[Region] )", "REMOVEFILTERS ( )"],
),
spec(
"SELECTEDVALUE",
FunctionCategory::Filter,
1,
2,
&[required("ColumnName", ParamKind::Column), optional("AlternateResult", ParamKind::Any)],
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Column, ParamKind::Any])],
ReturnType::Any,
EXCEL,
"Returns the value of a column when the filter context leaves exactly one distinct value, \
otherwise returns the alternate result (BLANK when omitted). Equivalent to \
IF ( HASONEVALUE ( column ), VALUES ( column ), alternate ).",
&["SELECTEDVALUE ( Product[Color] )", "SELECTEDVALUE ( Product[Color], \"Multiple colors\" )"],
),
spec(
"SHADOWCLUSTER",
FunctionCategory::Filter,
1,
1,
&[required("TableExpression", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
INTERNAL,
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, marks a table expression as a shadow so that \
it is only enabled inside an ALLSELECTED context. Used internally by Power BI composite \
models.",
&["SHADOWCLUSTER ( VALUES ( Product[Color] ) )"],
),
spec(
"WINDOW",
FunctionCategory::Filter,
2,
10,
&[
required("From", ParamKind::Number),
optional("FromType", ParamKind::Any),
required("To", ParamKind::Number),
optional("ToType", ParamKind::Any),
optional("Relation", ParamKind::Table),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("PartitionBy", ParamKind::Any),
optional("MatchBy", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Number, ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table]),
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
overload(&[
ParamKind::Number,
ParamKind::Any,
ParamKind::Number,
ParamKind::Any,
ParamKind::Table,
ParamKind::Any,
ParamKind::Any,
ParamKind::Any,
]),
overload(&[
ParamKind::Number,
ParamKind::Any,
ParamKind::Number,
ParamKind::Any,
ParamKind::Table,
ParamKind::Any,
ParamKind::Any,
ParamKind::Any,
ParamKind::Any,
]),
overload(&[
ParamKind::Number,
ParamKind::Any,
ParamKind::Number,
ParamKind::Any,
ParamKind::Table,
ParamKind::Any,
ParamKind::Any,
ParamKind::Any,
ParamKind::Any,
ParamKind::Any,
]),
],
ReturnType::Table,
INTERNAL,
"Returns the rows between a start and an end boundary within each partition of the \
relation, ordered by the ORDERBY clause. REL boundaries count rows from the current row \
while ABS boundaries are absolute positions in the partition; the result is a table.",
&["WINDOW ( 1, ABS, 1, ABS, Sales, ORDERBY ( Sales[OrderDate] ) )", "WINDOW ( -1, REL, 1, REL, Sales )"],
),
];
File diff suppressed because it is too large Load Diff
+993
View File
@@ -0,0 +1,993 @@
//! Information functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! The `INFO.*` records take no required arguments: dax.guide documents an optional, repeatable
//! `RestrictionName` / `RestrictionValue` pair for every one of them, so their arity is open and
//! the descriptive signature keeps both positions optional. The `INFO.VIEW.*` functions take no
//! arguments at all.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
/// An `INFO.*` table function with the shared optional restriction-pair syntax.
macro_rules! info {
($name:literal, $description:literal) => {
spec(
$name,
FunctionCategory::Information,
0,
usize::MAX,
&[optional("RestrictionName", ParamKind::Text), optional("RestrictionValue", ParamKind::Any)],
&[overload(&[]), overload(&[ParamKind::Text]), variadic(&[ParamKind::Text, ParamKind::Any])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
$description,
&[concat!($name, " ()")],
)
};
}
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"COLUMNSTATISTICS",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
"Returns one row per column visible in the model, with the table name, column name, \
minimum, maximum, cardinality and maximum string length. The statistics respect the \
security roles of the connected user.",
&["COLUMNSTATISTICS ()"],
),
spec(
"CONTAINS",
FunctionCategory::Information,
3,
usize::MAX,
&[required("Table", ParamKind::Table), required("ColumnName", ParamKind::Column), required("Value", ParamKind::Any)],
&[variadic(&[ParamKind::Table, ParamKind::Column, ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when at least one row of the table has all the supplied column/value \
pairs. Each pair is a column reference followed by the value to match, using strict \
equality (BLANK does not match 0).",
&["CONTAINS ( Product, Product[Color], \"Red\" )", "CONTAINS ( Sales, Sales[ProductKey], 1, Sales[Quantity], 2 )"],
),
spec(
"CONTAINSROW",
FunctionCategory::Information,
2,
usize::MAX,
&[required("Table", ParamKind::Table), required("Value", ParamKind::Any)],
&[variadic(&[ParamKind::Table, ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the table has a row whose values equal every supplied value, in \
column order. The IN operator executes this function; comparisons are strict, so \
BLANK does not match 0.",
// The first argument is the row to test against, so both examples pair a one-column table
// (a constructor, or a table expression) with exactly one scalar value.
&["CONTAINSROW ( { \"Red\", \"Blue\" }, \"Red\" )", "CONTAINSROW ( VALUES ( Sales[ProductKey] ), 1 )"],
),
spec(
"CONTAINSSTRING",
FunctionCategory::Information,
2,
2,
&[required("WithinText", ParamKind::Text), required("FindText", ParamKind::Text)],
&[overload(&[ParamKind::Text, ParamKind::Text])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when WithinText contains FindText. The comparison is case-insensitive and \
accent-sensitive; `?` and `*` are wildcards and `~?` / `~*` match them literally.",
&["CONTAINSSTRING ( Product[Product Name], \"red\" )", "CONTAINSSTRING ( \"Hello\", \"ell\" )"],
),
spec(
"CONTAINSSTRINGEXACT",
FunctionCategory::Information,
2,
2,
&[required("WithinText", ParamKind::Text), required("FindText", ParamKind::Text)],
&[overload(&[ParamKind::Text, ParamKind::Text])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when WithinText contains FindText using a case-sensitive and \
accent-sensitive comparison. Wildcards are not interpreted.",
&["CONTAINSSTRINGEXACT ( Product[Product Name], \"Red\" )", "CONTAINSSTRINGEXACT ( \"Hello\", \"Hell\" )"],
),
spec(
"CUSTOMDATA",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::String,
FunctionFlags::new(false, true, false, true, false),
"Returns the CustomData connection-string property supplied by the client, or an empty \
string when the connection did not define it. It does not inspect the data model or the \
filter context. GridCraft has no client connection string in a workbook, so the \
evaluator always answers the empty string.",
&["CUSTOMDATA ()"],
),
spec(
"EVALUATEANDLOG",
FunctionCategory::Information,
1,
3,
&[required("Value", ParamKind::Any), optional("Label", ParamKind::Text), optional("MaxRows", ParamKind::Number)],
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Text]), overload(&[ParamKind::Any, ParamKind::Text, ParamKind::Number])],
ReturnType::Variant,
FunctionFlags::new(false, false, false, false, false),
"Returns the first argument unchanged and writes its value to the DAX Evaluation Log \
trace event. The optional Label annotates the event; MaxRows caps the rows captured for \
a table expression and defaults to 10.",
&["EVALUATEANDLOG ( 1 )", "EVALUATEANDLOG ( [Sales Amount] )", "EVALUATEANDLOG ( Sales, \"Sales rows\", 5 )"],
),
spec(
"HASONEFILTER",
FunctionCategory::Information,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the column has exactly one distinct value resulting from direct \
filters on that column. Unlike HASONEVALUE it ignores filters propagated from related \
tables.",
&["HASONEFILTER ( Product[Color] )", "HASONEFILTER ( Sales[Quantity] )"],
),
spec(
"HASONEVALUE",
FunctionCategory::Information,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the filter context leaves exactly one distinct value in the column, \
regardless of whether the filter is direct or propagated through a relationship.",
&["HASONEVALUE ( Product[Category] )", "HASONEVALUE ( Sales[Quantity] )"],
),
info!(
"INFO.ALTERNATEOFDEFINITIONS",
"Exposes the TMSCHEMA_ALTERNATE_OF_DEFINITIONS data management view as a table; the \
optional restriction name/value pairs filter its rows."
),
info!(
"INFO.ANNOTATIONS",
"One row per annotation in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.ATTRIBUTEHIERARCHIES",
"Exposes the TMSCHEMA_ATTRIBUTE_HIERARCHIES schema rowset as a table; optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.ATTRIBUTEHIERARCHYSTORAGES",
"Exposes the TMSCHEMA_ATTRIBUTE_HIERARCHY_STORAGES data management view as a table; the \
optional restriction name/value pairs filter its rows."
),
info!(
"INFO.CALCDEPENDENCY",
"Reports which objects a DAX query depends on, so tools can inspect the dependency graph \
without parsing formulas."
),
info!(
"INFO.CALCULATIONGROUPS",
"Exposes the TMSCHEMA_CALCULATIONGROUPS data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.CALCULATIONITEMS",
"Exposes the TMSCHEMA_CALCULATIONITEMS data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.CALENDARCOLUMNGROUPS",
"Exposes the TMSCHEMA_CALENDAR_COLUMN_GROUPS schema rowset as a table; optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.CALENDARCOLUMNREFERENCES",
"Exposes the TMSCHEMA_CALENDAR_COLUMN_REFERENCES schema rowset as a table; optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.CALENDARS",
"Exposes the TMSCHEMA_CALENDARS schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.CATALOGS",
"Exposes the DBSCHEMA_CATALOGS schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.CHANGEDPROPERTIES",
"Exposes the TMSCHEMA_CHANGED_PROPERTIES schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.COLUMNPARTITIONSTORAGES",
"Exposes the TMSCHEMA_COLUMN_PARTITION_STORAGES data management view as a table; the \
optional restriction name/value pairs filter its rows."
),
info!(
"INFO.COLUMNPERMISSIONS",
"One row per column permission in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.COLUMNS",
"One row per column in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.COLUMNSTORAGES",
"One row per column storage in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.CSDLMETADATA",
"Provides the model metadata serialized as CSDL XML text, so a tool can read the \
conceptual schema without a client library."
),
info!(
"INFO.CULTURES",
"One row per culture in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.DATACOVERAGEDEFINITIONS",
"Exposes the TMSCHEMA_DATACOVERAGEDEFINITIONS data management view as a table; the \
optional restriction name/value pairs filter its rows."
),
info!(
"INFO.DATASOURCES",
"Exposes the TMSCHEMA_DATASOURCES schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.DELTATABLEMETADATASTORAGES",
"Exposes the TMSCHEMA_DELTA_TABLE_METADATA_STORAGES data management view as a table; the \
optional restriction name/value pairs filter its rows."
),
info!(
"INFO.DEPENDENCIES",
"Returns the dependency records of a DAX query, describing what the query reads from the \
model."
),
info!(
"INFO.DETAILROWSDEFINITIONS",
"One row per detail-rows definition in the model, with the columns of the matching \
schema rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.DICTIONARYSTORAGES",
"Exposes the TMSCHEMA_DICTIONARY_STORAGES data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.EXCLUDEDARTIFACTS",
"Exposes the TMSCHEMA_EXCLUDED_ARTIFACTS schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.EXPRESSIONS",
"One row per expression in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.EXTENDEDPROPERTIES",
"One row per extended property in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.FORMATSTRINGDEFINITIONS",
"Exposes the TMSCHEMA_FORMAT_STRING_DEFINITIONS data management view as a table; the \
optional restriction name/value pairs filter its rows."
),
info!(
"INFO.FUNCTIONS",
"Lists the DAX functions the engine makes available, one row per function. Optional \
restriction name/value pairs filter the rows."
),
info!(
"INFO.GENERALSEGMENTMAPSEGMENTMETADATASTORAGES",
"Exposes the TMSCHEMA_GENERAL_SEGMENT_MAP_SEGMENT_METADATA_STORAGES data management view \
as a table; the optional restriction name/value pairs filter its rows."
),
info!(
"INFO.GROUPBYCOLUMNS",
"Exposes the TMSCHEMA_GROUP_BY_COLUMNS data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.HIERARCHIES",
"Exposes the TMSCHEMA_HIERARCHIES schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.HIERARCHYSTORAGES",
"Exposes the TMSCHEMA_HIERARCHY_STORAGES data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.KPIS",
"One row per KPI in the model, with the columns of the matching schema rowset. Optional \
restriction name/value pairs filter the rows."
),
info!(
"INFO.LEVELS",
"One row per level in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.LINGUISTICMETADATA",
"Exposes the TMSCHEMA_LINGUISTIC_METADATA schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.MEASURES",
"One row per measure in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.MODEL",
"Exposes the TMSCHEMA_MODEL schema rowset as a table; optional restriction name/value \
pairs filter its rows."
),
info!(
"INFO.OBJECTTRANSLATIONS",
"One row per object translation in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.PARQUETFILESTORAGES",
"Exposes the TMSCHEMA_PARQUET_FILE_STORAGES data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.PARTITIONS",
"Exposes the TMSCHEMA_PARTITIONS schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.PARTITIONSTORAGES",
"One row per partition storage in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.PERSPECTIVECOLUMNS",
"One row per perspective column in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.PERSPECTIVEHIERARCHIES",
"One row per perspective hierarchy in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.PERSPECTIVEMEASURES",
"One row per perspective measure in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.PERSPECTIVES",
"One row per perspective in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.PERSPECTIVETABLES",
"One row per perspective table in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.PROPERTIES",
"Exposes the DISCOVER_PROPERTIES schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.QUERYGROUPS",
"Exposes the TMSCHEMA_QUERY_GROUPS data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.REFRESHPOLICIES",
"Exposes the TMSCHEMA_REFRESH_POLICIES data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.RELATEDCOLUMNDETAILS",
"Exposes the TMSCHEMA_RELATED_COLUMN_DETAILS data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.RELATIONSHIPINDEXSTORAGES",
"Exposes the TMSCHEMA_RELATIONSHIP_INDEX_STORAGES data management view as a table; the \
optional restriction name/value pairs filter its rows."
),
info!(
"INFO.RELATIONSHIPS",
"Exposes the TMSCHEMA_RELATIONSHIPS schema rowset as a table; optional restriction \
name/value pairs filter its rows."
),
info!(
"INFO.RELATIONSHIPSTORAGES",
"Exposes the TMSCHEMA_RELATIONSHIP_STORAGES data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.ROLEMEMBERSHIPS",
"One row per role membership in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.ROLES",
"One row per role in the model, with the columns of the matching schema rowset. Optional \
restriction name/value pairs filter the rows."
),
info!(
"INFO.SEGMENTMAPSTORAGES",
"One row per segment map storage in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.SEGMENTSTORAGES",
"Exposes the TMSCHEMA_SEGMENT_STORAGES data management view as a table; the optional \
restriction name/value pairs filter its rows."
),
info!(
"INFO.STORAGEFILES",
"One row per storage file in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.STORAGEFOLDERS",
"One row per storage folder in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.STORAGETABLECOLUMNS",
"Reports storage statistics for each column of the in-memory tables, so a tool can see \
how the model is packed."
),
info!(
"INFO.STORAGETABLECOLUMNSEGMENTS",
"Describes the column segments that hold data for the in-memory tables, one row per \
segment."
),
info!(
"INFO.TABLEPERMISSIONS",
"One row per table permission in the model, with the columns of the matching schema \
rowset. Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.TABLES",
"One row per table in the model, with the columns of the matching schema rowset. Optional \
restriction name/value pairs filter the rows."
),
info!(
"INFO.TABLESTORAGES",
"One row per table storage in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
info!(
"INFO.USERDEFINEDFUNCTIONS",
"Exposes the TMSCHEMA_FUNCTIONS schema rowset as a table; optional restriction name/value \
pairs filter its rows."
),
info!(
"INFO.VARIATIONS",
"One row per variation in the model, with the columns of the matching schema rowset. \
Optional restriction name/value pairs filter the rows."
),
spec(
"INFO.VIEW.COLUMNS",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
"Table of every column in the model, decoded so a query can use it without joins to \
other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
calculated columns and calculated tables.",
&["INFO.VIEW.COLUMNS ()"],
),
spec(
"INFO.VIEW.MEASURES",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
"Table of every measure in the model, decoded so a query can use it without joins to \
other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
calculated columns and calculated tables.",
&["INFO.VIEW.MEASURES ()"],
),
spec(
"INFO.VIEW.RELATIONSHIPS",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
"Table of every relationship in the model, decoded so a query can use it without joins \
to other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
calculated columns and calculated tables.",
&["INFO.VIEW.RELATIONSHIPS ()"],
),
spec(
"INFO.VIEW.TABLES",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
"Table of every table in the model, decoded so a query can use it without joins to other \
DMV rowsets. Unlike the plain INFO functions it is allowed in measures, calculated \
columns and calculated tables.",
&["INFO.VIEW.TABLES ()"],
),
spec(
"ISAFTER",
FunctionCategory::Information,
2,
usize::MAX,
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any), optional("Order", ParamKind::Logical)],
&[variadic(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the Value1/Value2 groups compare strictly after the corresponding \
values in the ascending/descending order given by each optional Order flag. The \
comparison uses the existing evaluation context; ISAFTER is not an iterator.",
&["ISAFTER ( Sales[Year], 2008 )", "ISAFTER ( Sales[Year], 2008, 1 )"],
),
spec(
"ISBLANK",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the value is BLANK. Zero and the empty string are not blank; the \
predicate is equivalent to the strict comparison `value == BLANK ()`.",
&["ISBLANK ( Sales[Amount] )", "ISBLANK ( BLANK () )"],
),
spec(
"ISBOOLEAN",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"TRUE for a Boolean value. Alias of ISLOGICAL.",
&["ISBOOLEAN ( TRUE )", "ISBOOLEAN ( Sales[Amount] )"],
),
spec(
"ISCROSSFILTERED",
FunctionCategory::Information,
1,
1,
&[required("TableNameOrColumnName", ParamKind::Reference)],
&[overload(&[ParamKind::Reference])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the table or column is cross-filtered, meaning a filter is applied to \
that table, to one of its columns, or to a column of a related table.",
&["ISCROSSFILTERED ( Product )", "ISCROSSFILTERED ( Product[Category] )"],
),
spec(
"ISDATETIME",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the value has the Date/time type.",
&["ISDATETIME ( DATE ( 2008, 1, 1 ) )", "ISDATETIME ( Sales[Order Date] )"],
),
spec(
"ISDECIMAL",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"TRUE for a fixed-precision decimal (Currency) value. Alias of ISCURRENCY.",
&["ISDECIMAL ( 1.5 )", "ISDECIMAL ( Sales[Net Price] )"],
),
spec(
"ISDOUBLE",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"TRUE for a floating-point decimal value.",
&["ISDOUBLE ( 1.5 )", "ISDOUBLE ( Sales[Amount] )"],
),
spec(
"ISEMPTY",
FunctionCategory::Information,
1,
1,
&[required("Table", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the table expression has no rows in the current evaluation context, \
including tables whose only row would be blank.",
&["ISEMPTY ( Sales )", "ISEMPTY ( FILTER ( Sales, FALSE ) )"],
),
spec(
"ISERROR",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when evaluating the value produces an error. It inspects the value, so the \
error is caught rather than propagated.",
&["ISERROR ( 1 / 0 )", "ISERROR ( Sales[Amount] )"],
),
spec(
"ISEVEN",
FunctionCategory::Information,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the number is even, FALSE when it is odd. Truncation applies to \
non-integers, matching the mathematical sign of the truncated value.",
&["ISEVEN ( 4 )", "ISEVEN ( Sales[Quantity] )"],
),
spec(
"ISFILTERED",
FunctionCategory::Information,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"TRUE when the column carries direct filters in the current context; filters propagated \
from a related table do not count, so use ISCROSSFILTERED for those.",
&["ISFILTERED ( Product[Color] )", "ISFILTERED ( Sales[Quantity] )"],
),
spec(
"ISINSCOPE",
FunctionCategory::Information,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the column is the level currently in scope in a hierarchy of levels, \
for example the group-by column of the current SUMMARIZECOLUMNS row.",
&["ISINSCOPE ( Product[Category] )", "ISINSCOPE ( Product[Subcategory] )"],
),
spec(
"ISINT64",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the value is a 64-bit integer. This is the alias of ISINTEGER.",
&["ISINT64 ( 1 )", "ISINT64 ( Sales[Quantity] )"],
),
spec(
"ISLOGICAL",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"TRUE for a logical value (TRUE or FALSE). Alias of ISBOOLEAN.",
&["ISLOGICAL ( FALSE )", "ISLOGICAL ( Sales[Amount] )"],
),
spec(
"ISNONTEXT",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the value is not text. A blank cell is not text, so ISNONTEXT also \
returns TRUE for BLANK.",
&["ISNONTEXT ( 1 )", "ISNONTEXT ( Product[Color] )"],
),
spec(
"ISNUMBER",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the value is a number. Text that looks numeric is not a number; use \
VALUE to convert it first.",
&["ISNUMBER ( 1 )", "ISNUMBER ( Sales[Amount] )"],
),
spec(
"ISNUMERIC",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"TRUE for an integer or decimal number, including Currency and floating-point values.",
&["ISNUMERIC ( 1.5 )", "ISNUMERIC ( Sales[Net Price] )"],
),
spec(
"ISODD",
FunctionCategory::Information,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the number is odd, FALSE when it is even. Non-integer values are \
truncated before the parity test.",
&["ISODD ( 3 )", "ISODD ( Sales[Quantity] )"],
),
spec(
"ISONORAFTER",
FunctionCategory::Information,
2,
usize::MAX,
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any), optional("Order", ParamKind::Logical)],
&[variadic(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the Value1/Value2 groups compare on or after the corresponding values \
in the order given by each optional Order flag, emulating a START AT clause. It is not \
an iterator.",
&["ISONORAFTER ( Sales[Year], 2008 )", "ISONORAFTER ( Sales[Year], 2008, 1 )"],
),
spec(
"ISSELECTEDMEASURE",
FunctionCategory::Information,
1,
usize::MAX,
&[required("Measure", ParamKind::Reference)],
&[variadic(&[ParamKind::Reference])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, false, true),
"Returns TRUE when the measure currently evaluated in a calculation item is one of the \
listed measures. A query measure redefined in the DAX query is not recognised.",
&["ISSELECTEDMEASURE ( [Sales Amount] )", "ISSELECTEDMEASURE ( [Sales Amount], [Sales Quantity] )"],
),
spec(
"ISSTRING",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the value is a string. This is the alias of ISTEXT; a blank value is \
not text.",
&["ISSTRING ( \"text\" )", "ISSTRING ( Product[Color] )"],
),
spec(
"ISSUBTOTAL",
FunctionCategory::Information,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Boolean,
FunctionFlags::new(false, false, true, true, true),
"Returns TRUE when the current SUMMARIZE row is the subtotal for the column, FALSE for a \
detail row. It only makes sense inside SUMMARIZE with ROLLUP; SUMMARIZECOLUMNS with \
ROLLUPADDISSUBTOTAL supersedes it.",
&["ISSUBTOTAL ( Product[Brand] )", "ISSUBTOTAL ( Product[Category] )"],
),
spec(
"ISTEXT",
FunctionCategory::Information,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, true),
"Returns TRUE when the value is text. This is the alias of ISSTRING; a blank value is not \
text.",
&["ISTEXT ( \"text\" )", "ISTEXT ( Product[Color] )"],
),
spec(
"NAMEOF",
FunctionCategory::Information,
1,
3,
&[required("Value", ParamKind::Reference), optional("Component", ParamKind::Text), optional("Escaped", ParamKind::Text)],
&[
overload(&[ParamKind::Reference]),
overload(&[ParamKind::Reference, ParamKind::Text]),
overload(&[ParamKind::Reference, ParamKind::Text, ParamKind::Text]),
],
ReturnType::String,
FunctionFlags::new(false, false, false, false, true),
"Text name of a table, column, measure or calendar. Component selects TABLE, COLUMN, \
MEASURE, CALENDAR, FULL, SELF or PARENT; Escaped selects ESCAPED, UNESCAPED or \
MINIMALLYESCAPED. Variables and dynamic expressions are not accepted.",
&["NAMEOF ( Sales[Amount] )", "NAMEOF ( [Sales Amount] )"],
),
spec(
"SELECTEDMEASURE",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::Any,
FunctionFlags::new(false, false, false, false, true),
"Returns a reference to the measure currently evaluated in a calculation item. During \
application each call is replaced by the selected measure, which also triggers context \
transition.",
&["SELECTEDMEASURE ()"],
),
spec(
"SELECTEDMEASUREFORMATSTRING",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::String,
FunctionFlags::new(false, false, false, false, true),
"Format string of the measure under evaluation in the current calculation item.",
&["SELECTEDMEASUREFORMATSTRING ()"],
),
spec(
"SELECTEDMEASURENAME",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::String,
FunctionFlags::new(false, false, false, false, true),
"Name of the measure under evaluation in the current calculation item, including one \
redefined in the DAX query.",
&["SELECTEDMEASURENAME ()"],
),
spec(
"TABLEOF",
FunctionCategory::Information,
1,
1,
&[required("Reference", ParamKind::Reference)],
&[overload(&[ParamKind::Reference])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, true),
"Resolves a column, measure or calendar reference to the table that owns it.",
&["TABLEOF ( Sales[Amount] )", "TABLEOF ( Product[Color] )"],
),
spec(
"TEXTCONTAINS",
FunctionCategory::Information,
2,
3,
&[required("WithinTextColumn", ParamKind::Column), required("SearchText", ParamKind::Text), optional("MatchMode", ParamKind::Text)],
&[overload(&[ParamKind::Column, ParamKind::Text]), overload(&[ParamKind::Column, ParamKind::Text, ParamKind::Text])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, false, false),
"TRUE when the column text matches SearchText under full-text query semantics. MatchMode \
is TEXTMATCHING (the default), FUZZYMATCHING or PHRASEMATCHING.",
&["TEXTCONTAINS ( Product[Product Name], \"red\" )", "TEXTCONTAINS ( Product[Product Name], \"red\", \"FUZZYMATCHING\" )"],
),
spec(
"TEXTSIMILARITY",
FunctionCategory::Information,
2,
3,
&[required("WithinTextColumn", ParamKind::Column), required("SearchText", ParamKind::Text), optional("MatchMode", ParamKind::Text)],
&[overload(&[ParamKind::Column, ParamKind::Text]), overload(&[ParamKind::Column, ParamKind::Text, ParamKind::Text])],
ReturnType::Decimal,
FunctionFlags::new(false, false, false, false, false),
"Returns the BM25 relevance score of the text in the column against the search text; a \
higher score is a stronger match and 0 means no match. MatchMode is TEXTMATCHING (the \
default), FUZZYMATCHING or PHRASEMATCHING. Scores are comparable only within the same \
search context.",
&["TEXTSIMILARITY ( Product[Product Name], \"red\" )", "TEXTSIMILARITY ( Product[Product Name], \"red\", \"FUZZYMATCHING\" )"],
),
spec(
"USERCULTURE",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::String,
FunctionFlags::new(false, true, false, false, true),
"Returns the culture code of the current user, such as \"en-US\", derived from the \
operating system or browser settings.",
&["USERCULTURE ()"],
),
spec(
"USERNAME",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::String,
FunctionFlags::new(false, true, false, true, false),
"The connection identity in domain\\user form, as supplied when the connection was \
opened.",
&["USERNAME ()"],
),
spec(
"USEROBJECTID",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::String,
FunctionFlags::new(false, true, false, false, false),
"Returns the current user's object ID from Azure AD, or the security identifier (SID) when \
the model runs on-premises.",
&["USEROBJECTID ()"],
),
spec(
"USERPRINCIPALNAME",
FunctionCategory::Information,
0,
0,
&[],
&[overload(&[])],
ReturnType::String,
FunctionFlags::new(false, true, false, false, false),
"Returns the user principal name of the current user, typically the email address in \
user@domain form.",
&["USERPRINCIPALNAME ()"],
),
];
+229
View File
@@ -0,0 +1,229 @@
//! Logical functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! The category holds three kinds of functions:
//!
//! - Boolean combinators (`AND`, `OR`, `NOT`) and the constants `TRUE`/`FALSE`, all of which
//! return a Boolean;
//! - bitwise integer operations (`BITAND`, `BITOR`, `BITXOR`), which are engine-only: dax.guide
//! does not list them for any Excel version;
//! - scalar selectors (`IF`, `IF.EAGER`, `IFERROR`, `SWITCH`, `COALESCE`), which return a value
//! whose type follows the selected branch and are therefore catalogued as
//! [`ReturnType::Any`].
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
/// Available to every host, with the usual DirectQuery restrictions.
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
/// Engine-only functions: no Excel version listed by dax.guide supports them.
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
/// Functions dax.guide flags as not recommended (`IFERROR`) or that are documented as an
/// optimisation-only escape hatch (`IF.EAGER`).
const DISCOURAGED: FunctionFlags = FunctionFlags::new(false, false, true, true, true);
/// `IF.EAGER` is engine-only and discouraged except for specific optimisations.
const EAGER: FunctionFlags = FunctionFlags::new(false, false, true, false, true);
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"AND",
FunctionCategory::Logical,
2,
2,
&[required("Logical1", ParamKind::Logical), required("Logical2", ParamKind::Logical)],
&[overload(&[ParamKind::Logical, ParamKind::Logical])],
ReturnType::Boolean,
STANDARD,
"Returns TRUE when both logical arguments are TRUE, and FALSE otherwise. The function \
accepts exactly two arguments; use the `&&` operator to combine three or more conditions \
without nesting. Like the operator, it does not short-circuit when evaluated eagerly.",
&["AND ( Sales[Amount] > 0, Sales[Quantity] > 0 )", "AND ( TRUE, FALSE )"],
),
spec(
"BITAND",
FunctionCategory::Logical,
2,
2,
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
ENGINE_ONLY,
"Returns the bitwise AND of two integers. Both arguments are converted to integers; the \
result is a signed 64-bit integer.",
&["BITAND ( 5, 3 )", "BITAND ( 13, 25 )"],
),
spec(
"BITOR",
FunctionCategory::Logical,
2,
2,
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
ENGINE_ONLY,
"Returns the bitwise OR of two integers. Both arguments are converted to integers; the \
result is a signed 64-bit integer.",
&["BITOR ( 5, 3 )", "BITOR ( 13, 25 )"],
),
spec(
"BITXOR",
FunctionCategory::Logical,
2,
2,
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
ENGINE_ONLY,
"Returns the bitwise XOR of two integers. Both arguments are converted to integers; the \
result is a signed 64-bit integer.",
&["BITXOR ( 5, 3 )", "BITXOR ( 13, 25 )"],
),
spec(
"COALESCE",
FunctionCategory::Logical,
2,
usize::MAX,
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any)],
&[variadic(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
ENGINE_ONLY,
"The first argument whose value is not BLANK; when every argument is blank the result is \
BLANK. At least two arguments are required, and later arguments are not evaluated once \
a non-blank value is found. Unlike a chain of IF/ISBLANK checks, the result type follows \
the first non-blank argument.",
&[
"COALESCE ( Sales[Discount], 0 )",
"COALESCE ( Store[Area Manager], \"** Not Assigned **\" )",
"COALESCE ( [Sales Amount], [Budget Amount], 0 )",
],
),
spec(
"FALSE",
FunctionCategory::Logical,
0,
0,
&[],
&[overload(&[])],
ReturnType::Boolean,
STANDARD,
"Returns the logical value FALSE. `FALSE` without parentheses is the same constant; FALSE \
is converted to 0 when a numeric result is required.",
&["FALSE ()", "IF ( Sales[Amount] > 0, TRUE (), FALSE () )"],
),
spec(
"IF",
FunctionCategory::Logical,
2,
3,
&[required("LogicalTest", ParamKind::Logical), required("ResultIfTrue", ParamKind::Any), optional("ResultIfFalse", ParamKind::Any)],
&[overload(&[ParamKind::Logical, ParamKind::Any]), overload(&[ParamKind::Logical, ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
STANDARD,
"Evaluates the logical test and returns `ResultIfTrue` when it is TRUE and \
`ResultIfFalse` otherwise. When the third argument is omitted a FALSE test returns \
BLANK. Only the selected branch is evaluated in the regular (strict) execution plan, and \
the result type follows the selected branch or the common type of both branches.",
&["IF ( Sales[Amount] > 0, 1, 0 )", "IF ( [Sales Amount] > 1000, \"Large\", \"Small\" )", "IF ( Sales[Quantity] > 0, Sales[Amount] )"],
),
spec(
"IF.EAGER",
FunctionCategory::Logical,
2,
3,
&[required("LogicalTest", ParamKind::Logical), required("ResultIfTrue", ParamKind::Any), optional("ResultIfFalse", ParamKind::Any)],
&[overload(&[ParamKind::Logical, ParamKind::Any]), overload(&[ParamKind::Logical, ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
EAGER,
"Same conditional semantics as IF, but forces an eager execution plan in which both \
branch expressions are evaluated before the test chooses one. It exists only for query \
optimisation and should be used only after measuring a clear advantage over IF; the \
result type is Variant when the branches differ.",
&["IF.EAGER ( Sales[Amount] > 0, 1, 0 )", "IF.EAGER ( [Sales Amount] > 1000, \"Large\", \"Small\" )"],
),
spec(
"IFERROR",
FunctionCategory::Logical,
2,
2,
&[required("Value", ParamKind::Any), required("ValueIfError", ParamKind::Any)],
&[overload(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
DISCOURAGED,
"Yields `ValueIfError` when the first argument raises an error, and otherwise repeats the \
first argument's value; faster than the equivalent \
`IF ( ISERROR ( Value ), ValueIfError, Value )`. Neither IFERROR nor ISERROR catches \
every runtime error, because block-mode execution can bypass the check, so both are \
discouraged.",
&["IFERROR ( 1 / 0, 0 )", "IFERROR ( VALUE ( Sales[Text] ), BLANK () )"],
),
spec(
"NOT",
FunctionCategory::Logical,
1,
1,
&[required("Logical", ParamKind::Logical)],
&[overload(&[ParamKind::Logical])],
ReturnType::Boolean,
STANDARD,
"Returns the opposite Boolean value: TRUE for a FALSE argument and FALSE for a TRUE \
argument. NOT is an operator exposed through function syntax.",
&["NOT ( Sales[Amount] > 0 )", "NOT ( TRUE )"],
),
spec(
"OR",
FunctionCategory::Logical,
2,
2,
&[required("Logical1", ParamKind::Logical), required("Logical2", ParamKind::Logical)],
&[overload(&[ParamKind::Logical, ParamKind::Logical])],
ReturnType::Boolean,
STANDARD,
"Returns TRUE when either logical argument is TRUE, and FALSE when both are FALSE. The \
function accepts exactly two arguments; use the `||` operator to combine three or more \
conditions without nesting.",
&["OR ( Sales[Amount] > 0, Sales[Quantity] > 0 )", "OR ( TRUE, FALSE )"],
),
spec(
"SWITCH",
FunctionCategory::Logical,
3,
usize::MAX,
&[
required("Expression", ParamKind::Any),
required("Value", ParamKind::Any),
required("Result", ParamKind::Any),
optional("Else", ParamKind::Any),
],
&[variadic(&[ParamKind::Any, ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
STANDARD,
"Compares the expression with each value in turn and returns the result paired with the \
first match; when nothing matches it returns the optional else argument, or BLANK when \
that argument is omitted. Values and results come in pairs, so the call needs an odd \
number of arguments when there is no else and an even number when there is one. All \
results and the else value must have the same data type. Using TRUE as the expression \
turns SWITCH into a cleaner alternative to cascading IF calls.",
&[
"SWITCH ( [X], 1, \"a\", 2, \"b\", \"other\" )",
"SWITCH ( Sales[Region], \"North\", 1, \"South\", 2, 0 )",
"SWITCH ( TRUE (), Sales[Amount] > 1000, \"Large\", Sales[Amount] > 100, \"Medium\", \"Small\" )",
],
),
spec(
"TRUE",
FunctionCategory::Logical,
0,
0,
&[],
&[overload(&[])],
ReturnType::Boolean,
STANDARD,
"Returns the logical value TRUE. `TRUE` without parentheses is the same constant; TRUE is \
converted to 1 when a numeric result is required.",
&["TRUE ()", "IF ( Sales[Amount] > 0, TRUE (), FALSE () )"],
),
];
+677
View File
@@ -0,0 +1,677 @@
//! Math and trigonometry functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"ABS",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Numeric,
standard(false),
"Absolute value of Number with the sign stripped and the numeric type kept (Currency, \
Decimal or Integer). Infinite values are accepted and nothing is rounded.",
&["ABS ( -1 )", "ABS ( [Amount] )"],
),
spec(
"ACOS",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the arccosine of a number in radians, in the range 0 to pi. The argument is the \
cosine of the angle and must be between -1 and 1; multiply the result by 180/PI() or \
use DEGREES to obtain degrees. Results are approximate Decimal values.",
&["ACOS ( 0.5 )"],
),
spec(
"ACOSH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the inverse hyperbolic cosine, in radians, of a number greater than or equal to \
1. ACOSH(COSH(x)) equals x when x is in range; the result is an approximate Decimal \
value.",
&["ACOSH ( 2 )"],
),
spec(
"ACOT",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Principal arccotangent of a real number, in radians between 0 and pi, as an approximate \
Decimal.",
&["ACOT ( 1 )"],
),
spec(
"ACOTH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Inverse hyperbolic cotangent of a number whose absolute value exceeds 1, as an \
approximate Decimal.",
&["ACOTH ( 2 )"],
),
spec(
"ASIN",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the arcsine of a number, in radians, between -pi/2 and pi/2. The argument is \
the sine of the angle and must be between -1 and 1; multiply by 180/PI() or use DEGREES \
for degrees. Results are approximate Decimal values.",
&["ASIN ( 0.5 )"],
),
spec(
"ASINH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the inverse hyperbolic sine of any real number, in radians. ASINH(SINH(x)) \
equals x; the result is an approximate Decimal value.",
&["ASINH ( 1 )"],
),
spec(
"ATAN",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the arctangent of a number, in radians, between -pi/2 and pi/2. Multiply by \
180/PI() or use DEGREES for degrees; the result is an approximate Decimal value.",
&["ATAN ( 0.5 )"],
),
spec(
"ATANH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Inverse hyperbolic tangent of a value strictly between -1 and 1, as an approximate \
Decimal. The endpoints -1 and 1, and anything outside that range, are errors.",
&["ATANH ( 0.5 )"],
),
spec(
"CEILING",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("Significance", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Numeric,
standard(false),
"Moves Number up to the closest multiple of Significance. Unlike ISO.CEILING, a \
negative significance makes CEILING round negative numbers toward negative infinity. \
The result usually follows the type of Significance, but a Currency Number stays \
Currency, a Boolean Significance yields Integer and a non-numeric Significance yields \
Decimal.",
&["CEILING ( 10.2, 1 )", "CEILING ( 10.7, 0.5 )"],
),
spec(
"CONVERT",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Expression", ParamKind::Any), required("DataType", ParamKind::Any)],
&[overload(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
standard(false),
"Converts an expression to the requested data type. The type is an unquoted keyword: \
BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64 or STRING/TEXT. \
Numeric conversions follow the target type's precision, so CURRENCY/DECIMAL rounds to \
four decimal places while DOUBLE keeps approximately 15 significant digits.",
&["CONVERT ( \"123\", INTEGER )", "CONVERT ( 12345, DATETIME )"],
),
spec(
"COS",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the cosine of an angle given in radians. Convert degrees with RADIANS or by \
multiplying by PI()/180; the result is an approximate Decimal value.",
&["COS ( PI () / 3 )"],
),
spec(
"COSH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Hyperbolic cosine of a real argument, as an approximate Decimal; it grows quickly as \
the argument rises.",
&["COSH ( 1 )"],
),
spec(
"COT",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the cotangent of an angle given in radians, computed as 1/TAN(angle). It is \
undefined at multiples of pi; the result is an approximate Decimal value.",
&["COT ( PI () / 4 )"],
),
spec(
"COTH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Hyperbolic cotangent of a hyperbolic angle in radians, computed as 1/TANH(angle); \
undefined at zero and returned as an approximate Decimal.",
&["COTH ( 1 )"],
),
spec(
"CURRENCY",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Value", ParamKind::Scalar)],
&[overload(&[ParamKind::Scalar])],
ReturnType::Currency,
standard(false),
"Converts a scalar expression to the Currency type, which stores four decimal places. \
The fifth significant decimal is rounded up when it is 5 or larger; TRUE becomes 1 and \
FALSE becomes 0, and numeric text is parsed. Currency values are fixed-point, so this \
conversion is not a general-purpose numeric cast.",
&["CURRENCY ( 10.5 )", "CURRENCY ( \"3.66666\" )"],
),
spec(
"DEGREES",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Converts an angle from radians to degrees by multiplying by 180/pi. The result is an \
approximate Decimal value; RADIANS performs the inverse conversion.",
&["DEGREES ( PI () / 2 )"],
),
spec(
"DIVIDE",
FunctionCategory::MathAndTrig,
2,
3,
&[required("Numerator", ParamKind::Number), required("Denominator", ParamKind::Number), optional("AlternateResult", ParamKind::Any)],
&[overload(&[ParamKind::Number, ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Any])],
ReturnType::Decimal,
standard(false),
"Performs safe division and returns an alternate result when the denominator is zero, \
avoiding the error or infinity produced by the / operator. The alternate result must be \
a constant and defaults to BLANK; the quotient is an approximate Decimal value. DIVIDE \
runs in the formula engine and is slower than native division when the denominator is \
known to be non-zero.",
&["DIVIDE ( 10, 2 )", "DIVIDE ( 10, 0, 0 )"],
),
spec(
"EVEN",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Rounds a number away from zero to the nearest even integer. An even integer is returned \
unchanged, and non-numeric input raises an error. The result is an exact Integer.",
&["EVEN ( 3.2 )", "EVEN ( -3.2 )"],
),
spec(
"EXP",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns e raised to the given power, the inverse of LN. The result is an approximate \
Decimal value with about 15 significant digits; for other bases use POWER or ^.",
&["EXP ( 1 )"],
),
spec(
"FACT",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the factorial of a non-negative number in Decimal form. A non-integer argument \
is truncated, and values above 170 overflow; the result is exact only through 21!. \
Calculated columns and RLS rules cannot use FACT in DirectQuery mode.",
&["FACT ( 5 )", "FACT ( 21 )"],
),
spec(
"FLOOR",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("Significance", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Moves Number toward zero to the closest multiple of Significance; both must share a \
sign. The result is always Decimal regardless of the argument types.",
&["FLOOR ( 2.7, 1 )", "FLOOR ( -2.7, -1 )"],
),
spec(
"GCD",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Greatest common divisor of two integers. Non-integer arguments are truncated before the \
calculation; the result is an exact Integer.",
&["GCD ( 36, 48 )"],
),
spec(
"INT",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Any,
standard(false),
"Rounds a number down toward negative infinity to an integer, so INT(-2.1) is -3. The \
result is Integer for Integer or Decimal input and Currency for Currency input; unlike \
TRUNC, the result type follows the argument and negative values move away from zero.",
&["INT ( -2.9 )", "INT ( 2.9 )"],
),
spec(
"ISO.CEILING",
FunctionCategory::MathAndTrig,
1,
2,
&[required("Number", ParamKind::Number), optional("Significance", ParamKind::Number)],
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Numeric,
standard(false),
"Moves Number up to the closest multiple of Significance using ISO rules. When \
Significance is omitted it defaults to 1; negative numbers and negative significance \
can round differently from CEILING. The result keeps the numeric type of Number, with \
Decimal precision when required by the multiple.",
&["ISO.CEILING ( 10.2 )", "ISO.CEILING ( 10.7, 0.5 )"],
),
spec(
"LCM",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Least common multiple of two integers: the smallest positive value that both arguments \
divide without a remainder. Non-integer arguments are truncated; the result is an exact \
Integer.",
&["LCM ( 4, 6 )"],
),
spec(
"LN",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the natural logarithm (base e) of a positive number. Zero and negative numbers \
produce an error; the result is an approximate Decimal value and is the inverse of EXP.",
&["LN ( 10 )"],
),
spec(
"LOG",
FunctionCategory::MathAndTrig,
1,
2,
&[required("Number", ParamKind::Number), optional("Base", ParamKind::Number)],
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the logarithm of a positive number in the given base; omitting the base uses \
10. The result is an approximate Decimal value, and LOG10 is the fixed base-10 \
shortcut.",
&["LOG ( 1000 )", "LOG ( 8, 2 )"],
),
spec(
"LOG10",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Base-10 logarithm of a positive number, as an approximate Decimal; the same value as \
LOG(number, 10).",
&["LOG10 ( 10000 )"],
),
spec(
"MOD",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("Divisor", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Any,
standard(false),
"Returns the remainder after dividing Number by Divisor. The result follows the operand \
type (Integer, Currency or Decimal) and its sign follows the divisor; a zero divisor \
produces an error. QUOTIENT returns the corresponding integer portion.",
&["MOD ( 7, 3 )", "MOD ( 8, 3 )"],
),
spec(
"MROUND",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("Multiple", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Rounds a number to the nearest multiple, rounding away from zero when the remainder is \
at least half the multiple. Number and Multiple must have the same sign; for decimal \
multiples the midpoint direction is undefined, so MROUND(6.05, 0.1) can differ from \
MROUND(7.05, 0.1). The result is Decimal.",
&["MROUND ( 7.3, 0.5 )"],
),
spec(
"ODD",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Rounds a number away from zero to the nearest odd integer. An odd integer is returned \
unchanged, and non-numeric input raises an error. The result is an exact Integer.",
&["ODD ( 2.1 )", "ODD ( -2.1 )"],
),
spec(
"PI",
FunctionCategory::MathAndTrig,
0,
0,
&[],
&[overload(&[])],
ReturnType::Decimal,
standard(false),
"The constant pi (3.14159265358979) as an approximate Decimal, accurate to 15 digits. \
Takes no arguments.",
&["PI ()"],
),
spec(
"POWER",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("Power", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns Number raised to Power. It is equivalent to the ^ operator and produces an \
approximate Decimal value; fractional powers of negative bases produce an error.",
&["POWER ( 2, 10 )", "POWER ( 9, 0.5 )"],
),
spec(
"QUOTIENT",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Numerator", ParamKind::Number), required("Denominator", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Whole-number part of dividing Numerator by Denominator, with the fraction cut toward \
zero. The result is an exact Integer and a zero denominator is an error; MOD gives the \
remainder.",
&["QUOTIENT ( 7, 2 )", "QUOTIENT ( -7, 2 )"],
),
spec(
"RADIANS",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Converts an angle from degrees to radians by multiplying by pi/180. The result is an \
approximate Decimal value; DEGREES performs the inverse conversion.",
&["RADIANS ( 180 )"],
),
spec(
"RAND",
FunctionCategory::MathAndTrig,
0,
0,
&[],
&[overload(&[])],
ReturnType::Decimal,
FunctionFlags::new(false, true, false, true, true),
"Returns a random Decimal value in [0, 1), uniformly distributed. RAND is volatile: it \
may return a different value on every evaluation and changes on recalculation, so it \
cannot be used where a stable result is required.",
&["RAND ()"],
),
spec(
"RANDBETWEEN",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Bottom", ParamKind::Number), required("Top", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
FunctionFlags::new(false, true, false, true, true),
"Returns a random Integer between Bottom and Top inclusive. Both bounds are integers; \
if Bottom is greater than Top the function raises an error. RANDBETWEEN is volatile, so \
it recalculates to a different value and is unsuitable for stable results.",
&["RANDBETWEEN ( 5, 50 )"],
),
spec(
"ROUND",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Rounds a number to the specified number of digits, using half away from zero. A positive \
count rounds right of the decimal point, zero rounds to an integer and a negative count \
rounds left of it. The result is a Decimal, so large integers can lose precision beyond \
about 15 significant digits.",
&["ROUND ( 3.14159, 2 )", "ROUND ( 1234, -2 )"],
),
spec(
"ROUNDDOWN",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Moves Number toward zero to the requested digit. Positive counts work right of the \
decimal point, zero rounds to an integer and negative counts work left of it; the \
result is Decimal and differs from FLOOR for negative numbers.",
&["ROUNDDOWN ( 2.71828, 3 )", "ROUNDDOWN ( -3.14159, 2 )"],
),
spec(
"ROUNDUP",
FunctionCategory::MathAndTrig,
2,
2,
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Moves Number away from zero to the requested digit, so 2.31 at one digit becomes 2.4. \
Positive counts work right of the decimal point, zero rounds to an integer and negative \
counts work left of it; the result is Decimal.",
&["ROUNDUP ( 3.14159, 2 )", "ROUNDUP ( -3.14159, 2 )"],
),
spec(
"SIGN",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Returns the sign of a real number: 1 when positive, 0 when zero and -1 when negative. \
The result is an exact Integer; infinite values are not supported.",
&["SIGN ( -5 )", "SIGN ( 0 )"],
),
spec(
"SIN",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the sine of an angle given in radians. Convert degrees with RADIANS or by \
multiplying by PI()/180; the result is an approximate Decimal value.",
&["SIN ( PI () / 6 )"],
),
spec(
"SINH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Hyperbolic sine of a real argument, as an approximate Decimal; ASINH is its inverse.",
&["SINH ( 1 )"],
),
spec(
"SQRT",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Square root of a non-negative number, as an approximate Decimal; a negative argument is \
an error. SQRTPI multiplies by pi before taking the root.",
&["SQRT ( 16 )"],
),
spec(
"SQRTPI",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Square root of Number multiplied by pi, as an approximate Decimal; negative input is an \
error, and SQRTPI(n) equals SQRT(n * PI()).",
&["SQRTPI ( 3 )"],
),
spec(
"TAN",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Returns the tangent of an angle given in radians. Convert degrees with RADIANS or by \
multiplying by PI()/180; the result is an approximate Decimal value and is undefined at \
odd multiples of pi/2.",
&["TAN ( PI () / 4 )"],
),
spec(
"TANH",
FunctionCategory::MathAndTrig,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Hyperbolic tangent of a real argument, computed as SINH(number)/COSH(number); the value \
lies between -1 and 1.",
&["TANH ( 1 )"],
),
spec(
"TRUNC",
FunctionCategory::MathAndTrig,
1,
2,
&[required("Number", ParamKind::Number), optional("NumberOfDigits", ParamKind::Number)],
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Truncates a number toward zero by removing its fractional part or the digits beyond the \
requested precision. NumberOfDigits defaults to 0, positive counts keep decimal places \
and negative counts truncate left of the decimal point. The result is always Decimal, \
unlike INT, which rounds toward negative infinity and follows the input type.",
&["TRUNC ( 3.14159 )", "TRUNC ( 3.14159, 2 )"],
),
];
+298
View File
@@ -0,0 +1,298 @@
//! Other functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! The category collects the bit-shift operators, the row-context helpers, the window ranking
//! functions, the metadata table function and the remaining special functions that dax.guide
//! lists under "Other". `INFO.STORAGETABLES` keeps the exact dotted spelling and shares the
//! optional restriction-pair syntax of the other `INFO.*` functions.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"BITLSHIFT",
FunctionCategory::Other,
2,
2,
&[required("Number", ParamKind::Number), required("ShiftAmount", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
FunctionFlags::new(false, false, false, true, true),
"Shifts the first argument's integer left by ShiftAmount bits; a negative amount shifts \
right. Two's-complement semantics, so the result can overflow or underflow.",
&["BITLSHIFT ( 4, 2 )", "BITLSHIFT ( Sales[Quantity], 1 )"],
),
spec(
"BITRSHIFT",
FunctionCategory::Other,
2,
2,
&[required("Number", ParamKind::Number), required("ShiftAmount", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
FunctionFlags::new(false, false, false, true, true),
"Shifts the first argument's integer right by ShiftAmount bits; a negative amount shifts \
left. Two's-complement semantics, so the result can overflow or underflow.",
&["BITRSHIFT ( 8, 2 )", "BITRSHIFT ( Sales[Quantity], 1 )"],
),
spec(
"BLANK",
FunctionCategory::Other,
0,
0,
&[],
&[overload(&[])],
ReturnType::Blank,
FunctionFlags::new(false, false, false, true, true),
"Returns the BLANK value. BLANK has no data type and is converted automatically when \
compared with other values; use the `==` operator or ISBLANK to test for it.",
&["BLANK ()"],
),
spec(
"EARLIER",
FunctionCategory::Other,
1,
2,
&[required("ColumnName", ParamKind::Column), optional("Number", ParamKind::Number)],
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Column, ParamKind::Number])],
ReturnType::Any,
FunctionFlags::new(false, false, true, true, true),
"Returns the value of a column in an outer row context, `Number` evaluation passes back \
(default 1). Fails when no outer row context exists. dax.guide marks it not recommended: \
a variable captured before the inner row context is easier to read and maintain.",
&["EARLIER ( Customer[Yearly Income] )", "EARLIER ( Customer[Yearly Income], 1 )"],
),
spec(
"EARLIEST",
FunctionCategory::Other,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Any,
FunctionFlags::new(false, false, true, true, true),
"Returns the value of a column in the outermost row context, equivalent to EARLIER with \
the largest possible scan count. dax.guide marks it not recommended in favour of storing \
the value in a variable.",
&["EARLIEST ( Customer[Yearly Income] )"],
),
spec(
"ERROR",
FunctionCategory::Other,
1,
1,
&[required("ErrorText", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::Variant,
FunctionFlags::new(false, false, false, true, true),
"Stops evaluation and raises a user-specified error with the supplied message. It can be \
used anywhere a scalar is expected, but has no data type of its own, so wrap it in \
CONVERT to give the surrounding expression a concrete type.",
&["ERROR ( \"Missing inflation rate\" )"],
),
spec(
"EXTERNALMEASURE",
FunctionCategory::Other,
1,
3,
&[required("MeasureName", ParamKind::Text), optional("Type", ParamKind::Text), optional("Datasource", ParamKind::Text)],
&[
overload(&[ParamKind::Text]),
overload(&[ParamKind::Text, ParamKind::Text]),
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text]),
],
ReturnType::Any,
FunctionFlags::new(false, false, false, false, true),
"Invokes a measure defined in a remote model. The optional type name \
(BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64, STRING/TEXT, \
VARIANT) declares the remote result type and the optional data source names the \
external model. Power BI generates these calls for composite models.",
&["EXTERNALMEASURE ( \"Remote Sales\", \"DOUBLE\", \"RemoteModel\" )"],
),
spec(
"HASH",
FunctionCategory::Other,
1,
usize::MAX,
&[required("Expression", ParamKind::Any)],
&[variadic(&[ParamKind::Any])],
ReturnType::Integer,
FunctionFlags::new(false, false, false, false, false),
"Fingerprints a variable number of input expressions with a hash and returns an integer. \
The function appears in the engine metadata but is not documented by Microsoft, so its \
exact hash algorithm and stability across versions are unspecified.",
&["HASH ( Sales[Amount] )", "HASH ( Sales[OrderNumber], Sales[LineNumber] )"],
),
spec(
"INFO.STORAGETABLES",
FunctionCategory::Other,
0,
usize::MAX,
&[optional("RestrictionName", ParamKind::Text), optional("RestrictionValue", ParamKind::Any)],
&[overload(&[]), overload(&[ParamKind::Text]), variadic(&[ParamKind::Text, ParamKind::Any])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
"Returns statistics about the in-memory storage tables of the model, with one row per \
table and columns such as DATABASE_NAME, TABLE_ID, TABLE_PARTITIONS_COUNT and \
ROWS_COUNT. It corresponds to the DISCOVER_STORAGE_TABLES dynamic management view, \
accepts optional restriction name/value pairs, and, like every INFO function, cannot be \
used in calculated tables or calculated columns.",
&["INFO.STORAGETABLES ()", "INFO.STORAGETABLES ( \"DATABASE_NAME\", \"Sales\" )"],
),
spec(
"ISATLEVEL",
FunctionCategory::Other,
1,
1,
&[required("Column", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, false, false),
"TRUE when the given column appears at the current level of the visual calculation data \
grid. Use it to apply different formatting or logic per hierarchy level.",
&["ISATLEVEL ( 'Date'[Year] )", "ISATLEVEL ( Product[Category] )"],
),
spec(
"ISCURRENCY",
FunctionCategory::Other,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, false, true),
"TRUE for a fixed-precision decimal (Currency) value. Alias of ISDECIMAL.",
&["ISCURRENCY ( Sales[Amount] )", "ISCURRENCY ( 1.5 )"],
),
spec(
"ISINTEGER",
FunctionCategory::Other,
1,
1,
&[required("Value", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, false, true),
"TRUE for an integer Value. Alias of ISINT64.",
&["ISINTEGER ( Sales[Quantity] )", "ISINTEGER ( 2.5 )"],
),
spec(
"KEYWORDMATCH",
FunctionCategory::Other,
2,
2,
&[required("MatchExpression", ParamKind::Text), required("Text", ParamKind::Text)],
&[overload(&[ParamKind::Text, ParamKind::Text])],
ReturnType::Boolean,
FunctionFlags::new(false, false, false, true, false),
"Returns TRUE when the match expression matches the supplied text. dax.guide lists it as \
deprecated: it was never released and only appeared in some Excel versions.",
&["KEYWORDMATCH ( \"bike\", \"Mountain Bike\" )"],
),
spec(
"RANK",
FunctionCategory::Other,
0,
7,
&[
optional("Ties", ParamKind::Text),
optional("Relation", ParamKind::Table),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Text),
optional("PartitionBy", ParamKind::Any),
optional("MatchBy", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[]),
overload(&[ParamKind::Text]),
overload(&[ParamKind::Text, ParamKind::Table]),
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any]),
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text]),
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any]),
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Integer,
FunctionFlags::new(false, false, false, false, true),
"Returns the rank of the current row inside its partition, ordered by an ORDERBY clause. \
The optional Ties argument selects DENSE or SKIP (SKIP is the default), Blanks controls \
where blank ordering values sort, PARTITIONBY splits the table, MATCHBY identifies the \
current row and Reset restarts the numbering. Relation defaults to ALLSELECTED of the \
ordering and partitioning columns, and either Relation or ORDERBY must be supplied.",
&["RANK ( DENSE, Sales, ORDERBY ( Sales[Amount] ) )", "RANK ( SKIP, Sales, ORDERBY ( Sales[Amount], DESC ) )"],
),
spec(
"ROWNUMBER",
FunctionCategory::Other,
0,
6,
&[
optional("Relation", ParamKind::Table),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Text),
optional("PartitionBy", ParamKind::Any),
optional("MatchBy", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[]),
overload(&[ParamKind::Table]),
overload(&[ParamKind::Table, ParamKind::Any]),
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text]),
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any]),
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Integer,
FunctionFlags::new(false, false, false, false, true),
"Returns the unique row number of the current row inside its partition, ordered by an \
ORDERBY clause. Unlike RANK, ties receive different numbers. The optional Blanks, \
PARTITIONBY, MATCHBY and Reset arguments behave as they do for RANK; either Relation or \
ORDERBY must be supplied.",
&["ROWNUMBER ( Sales, ORDERBY ( Sales[Amount] ) )", "ROWNUMBER ( Sales, ORDERBY ( Sales[OrderDate] ), LAST )"],
),
spec(
"SAMPLECARTESIANPOINTSBYCOVER",
FunctionCategory::Other,
4,
7,
&[
required("Size", ParamKind::Number),
required("Table", ParamKind::Table),
required("XAxis", ParamKind::Column),
required("YAxis", ParamKind::Column),
optional("Radius", ParamKind::Column),
optional("MaxMinRatio", ParamKind::Number),
optional("MaxBlankRatio", ParamKind::Number),
],
&[
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column, ParamKind::Column]),
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column, ParamKind::Column, ParamKind::Number]),
overload(&[
ParamKind::Number,
ParamKind::Table,
ParamKind::Column,
ParamKind::Column,
ParamKind::Column,
ParamKind::Number,
ParamKind::Number,
]),
],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, false),
"Returns a sample of at most `Size` rows from a table, chosen by plotting each row as a \
point on the X and Y coordinates and then dropping overlapping points. The optional \
Radius column controls point size, MaxMinRatio limits the ratio between the largest and \
smallest drawn points, and MaxBlankRatio limits the ratio between the largest point and \
those with a blank radius. The function is used by the engine's scatter chart sampling \
and is not documented by Microsoft.",
&[
"SAMPLECARTESIANPOINTSBYCOVER ( 1000, Sales, Sales[Longitude], Sales[Latitude] )",
"SAMPLECARTESIANPOINTSBYCOVER ( 1000, Sales, Sales[X], Sales[Y], Sales[Radius], 4, 0.1 )",
],
),
];
+107
View File
@@ -0,0 +1,107 @@
//! Parent-child functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! These five functions flatten a parent-child hierarchy into a delimited path. The delimiter
//! is always the vertical bar (`|`); `PATH` produces the string, `PATHLENGTH` counts its items,
//! `PATHCONTAINS` searches it, and `PATHITEM`/`PATHITEMREVERSE` extract one item from the left
//! or the right end.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
const FLAGS: FunctionFlags = standard(false);
/// dax.guide lists the parent-child functions in this order: PATH, PATHCONTAINS, PATHITEM,
/// PATHITEMREVERSE and PATHLENGTH.
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"PATH",
FunctionCategory::ParentChild,
2,
2,
&[required("ID_ColumnName", ParamKind::Column), required("Parent_ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column, ParamKind::Column])],
ReturnType::String,
FLAGS,
"Returns a text string containing the delimited list of IDs that starts at the top of a \
parent-child hierarchy and ends with the current row, separating the identifiers with \
the vertical bar. Both arguments must be column references, not expressions, and must \
share a data type (integer or text); the parent value must exist in the ID column. A \
blank parent returns just the ID, a blank ID returns BLANK, and an ID that contains a \
vertical bar returns an error. Duplicate IDs with different parents return an error; \
with the same parent the common parent is returned.",
&["PATH ( Account[AccountKey], Account[ParentAccountKey] )", "PATH ( Employee[EmployeeKey], Employee[ParentEmployeeKey] )"],
),
spec(
"PATHCONTAINS",
FunctionCategory::ParentChild,
2,
2,
&[required("Path", ParamKind::Text), required("Item", ParamKind::Any)],
&[overload(&[ParamKind::Text, ParamKind::Any])],
ReturnType::Boolean,
FLAGS,
"Returns TRUE when the item appears as a whole segment of the delimited path, and FALSE \
otherwise. The path is normally the result of PATH. An integer item is converted to \
text before the comparison; when that conversion fails the function returns an error.",
&["PATHCONTAINS ( Account[AccountPath], 2 )", "PATHCONTAINS ( Account[AccountPath], \"24\" )", "PATHCONTAINS ( \"1|24|2\", 2 )"],
),
spec(
"PATHITEM",
FunctionCategory::ParentChild,
2,
3,
&[required("Path", ParamKind::Text), required("Position", ParamKind::Number), optional("Type", ParamKind::Any)],
&[overload(&[ParamKind::Text, ParamKind::Number]), overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Any])],
ReturnType::Any,
FLAGS,
"Returns the item at the given position in the delimited path, counting from the left \
end where 1 is the top of the hierarchy. A position below 1 or beyond the number of \
items returns BLANK. The optional Type selects the result: TEXT (or 0), the default, \
returns a string, while INTEGER (or 1) converts the item to an integer. The result \
type therefore follows the Type argument. An invalid Type enumeration raises an error.",
&[
"PATHITEM ( Account[AccountPath], 1 )",
"PATHITEM ( Account[AccountPath], 2, INTEGER )",
"PATHITEM ( Account[AccountPath], 3, TEXT )",
"PATHITEM ( \"123|456|789|764\", 2 )",
],
),
spec(
"PATHITEMREVERSE",
FunctionCategory::ParentChild,
2,
3,
&[required("Path", ParamKind::Text), required("Position", ParamKind::Number), optional("Type", ParamKind::Any)],
&[overload(&[ParamKind::Text, ParamKind::Number]), overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Any])],
ReturnType::Any,
FLAGS,
"Returns the item at the given position in the delimited path, counting backwards from \
the last item, so position 1 is the current item and position 2 is its immediate \
parent. A position below 1 or beyond the number of items returns BLANK. The optional \
Type selects the result: TEXT (or 0), the default, returns a string, while INTEGER (or \
1) converts the item to an integer, so the result type follows the Type argument. An \
invalid Type enumeration raises an error.",
&[
"PATHITEMREVERSE ( Account[AccountPath], 1 )",
"PATHITEMREVERSE ( Account[AccountPath], 2, INTEGER )",
"PATHITEMREVERSE ( Account[AccountPath], 3, TEXT )",
"PATHITEMREVERSE ( \"123|456|789|764\", 2 )",
],
),
spec(
"PATHLENGTH",
FunctionCategory::ParentChild,
1,
1,
&[required("Path", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::Integer,
FLAGS,
"Counts the items in a delimited path, the current item included, so a root node's path \
has length 1. The path is normally the result of PATH, but any text with vertical-bar \
separators (including a literal such as \"123|456|789|764\") is accepted.",
&["PATHLENGTH ( Account[AccountPath] )", "PATHLENGTH ( \"123|456|789|764\" )"],
),
];
+107
View File
@@ -0,0 +1,107 @@
//! Relationship management functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! The four functions mirror <https://dax.guide/functions/relationships-management/> in index
//! order. `CROSSFILTER` and `USERELATIONSHIP` are filter modifiers: they return no value and
//! only alter filter propagation while the filter context that contains them is evaluated.
//! `RELATED` and `RELATEDTABLE` traverse an existing relationship from a row context.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, Overload, ParamKind, Parameter, ReturnType, overload, required, spec, standard};
/// Signature of `CROSSFILTER`, which names both endpoint columns and a direction.
const CROSSFILTER_PARAMS: &[Parameter] =
&[required("LeftColumnName", ParamKind::Column), required("RightColumnName", ParamKind::Column), required("CrossFilterType", ParamKind::Any)];
const CROSSFILTER_OVERLOADS: &[Overload] = &[overload(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])];
const USERELATIONSHIP_PARAMS: &[Parameter] = &[required("ColumnName1", ParamKind::Column), required("ColumnName2", ParamKind::Column)];
const USERELATIONSHIP_OVERLOADS: &[Overload] = &[overload(&[ParamKind::Column, ParamKind::Column])];
/// Flags shared by the relationship management functions: none of them is an iterator or
/// volatile, dax.guide recommends all of them, and every one is usable in Excel and restricted
/// by DirectQuery exactly like the rest of the catalog.
const RELATIONSHIP_FLAGS: FunctionFlags = standard(false);
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"CROSSFILTER",
FunctionCategory::RelationshipManagement,
3,
3,
CROSSFILTER_PARAMS,
CROSSFILTER_OVERLOADS,
ReturnType::Any,
RELATIONSHIP_FLAGS,
"Overrides the cross-filter direction of an existing relationship for the duration of \
the filter context it modifies. The two column arguments identify the relationship \
endpoints; the third argument is one of the words NONE, ONE, ONEWAY, BOTH, TWOWAY, \
ONEWAY_LEFTFILTERSRIGHT or ONEWAY_RIGHTFILTERSLEFT (the last two flow from the first \
column argument's table to the second's, or back). It changes filter propagation between \
the two tables, never which relationship is active — activating an inactive relationship \
is USERELATIONSHIP's job — so it is used as a filter modifier inside CALCULATE and \
similar functions and returns no value.",
&[
"CALCULATE ( [Sales Amount], CROSSFILTER ( Sales[CustomerKey], Customer[CustomerKey], BOTH ) )",
"CALCULATE ( COUNTROWS ( Customer ), CROSSFILTER ( Sales[ProductKey], 'Product'[ProductKey], NONE ) )",
"CALCULATE ( [Sales Amount], CROSSFILTER ( Sales[CustomerKey], Customer[CustomerKey], TWOWAY ) )",
],
),
spec(
"RELATED",
FunctionCategory::RelationshipManagement,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Any,
RELATIONSHIP_FLAGS,
"Returns the value of a column on the one side of a many-to-one relationship, following \
one or more regular relationships from the current row. It requires a row context and \
an active regular relationship, so it is used in calculated columns and inside table \
iterators; a limited relationship cannot be traversed. The result is BLANK when no \
related row exists and the column value can be of any type.",
&[
"SUMX ( Sales, Sales[Quantity] * RELATED ( 'Product'[List Price] ) )",
"RELATED ( 'Product'[Category] )",
"RELATED ( Customer[CountryRegion] )",
],
),
spec(
"RELATEDTABLE",
FunctionCategory::RelationshipManagement,
1,
1,
&[required("Table", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
RELATIONSHIP_FLAGS,
"Returns the rows of a table on the many side of a relationship, filtered to the rows \
related to the current row. It performs a context transition from the row context to a \
filter context before evaluating the table, making it a shortcut for CALCULATETABLE \
with no additional filters; unlike CALCULATETABLE it accepts only a table reference, \
not an arbitrary table expression.",
&["AVERAGEX ( Customer, COUNTROWS ( RELATEDTABLE ( Sales ) ) )", "RELATEDTABLE ( Sales )", "COUNTROWS ( RELATEDTABLE ( OrderLines ) )"],
),
spec(
"USERELATIONSHIP",
FunctionCategory::RelationshipManagement,
2,
2,
USERELATIONSHIP_PARAMS,
USERELATIONSHIP_OVERLOADS,
ReturnType::Any,
RELATIONSHIP_FLAGS,
"Activates an existing relationship for the duration of the filter context it modifies, \
so its filters propagate even when the relationship is inactive in the model. The two \
column arguments are the relationship endpoints; the innermost USERELATIONSHIP wins in \
nested CALCULATE expressions. It selects which relationship propagates filters, not \
their cross-filter direction, and returns no value.",
&[
"CALCULATE ( [Sales Amount], USERELATIONSHIP ( Sales[Delivery Date], 'Date'[Date] ) )",
"CALCULATE ( COUNTROWS ( Sales ), USERELATIONSHIP ( Sales[Order Date], 'Date'[Date] ) )",
],
),
];
+584
View File
@@ -0,0 +1,584 @@
//! Statistical functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples. The order matches
//! <https://dax.guide/functions/statistical/>.
//!
//! `LINEST`, `LINESTX` and `SAMPLE` have open-ended signatures: their repeated column/expression
//! groups (and the trailing `Const`/`Order` argument) are modelled with a variadic overload and
//! [`usize::MAX`] as the upper arity bound. All other functions have a closed arity range.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard, variadic};
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"BETA.DIST",
FunctionCategory::Statistical,
4,
6,
&[
required("X", ParamKind::Number),
required("Alpha", ParamKind::Number),
required("Beta", ParamKind::Number),
required("Cumulative", ParamKind::Logical),
optional("A", ParamKind::Number),
optional("B", ParamKind::Number),
],
&[
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical]),
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical, ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical, ParamKind::Number, ParamKind::Number]),
],
ReturnType::Decimal,
standard(false),
"Beta distribution on the interval [A, B]. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function. Omitting A and B uses the standard beta distribution on [0, 1]; Alpha and Beta must be positive, X must lie within [A, B], and a BLANK bound is an error rather than an omitted argument.",
&["BETA.DIST ( 0.5, 3.51, 4.02, TRUE, 0, 1 )", "BETA.DIST ( 0.5, 3.51, 4.02, FALSE )"],
),
spec(
"BETA.INV",
FunctionCategory::Statistical,
3,
5,
&[
required("Probability", ParamKind::Number),
required("Alpha", ParamKind::Number),
required("Beta", ParamKind::Number),
optional("A", ParamKind::Number),
optional("B", ParamKind::Number),
],
&[
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number]),
],
ReturnType::Decimal,
standard(false),
"Inverse of the beta cumulative distribution function: returns the x for which BETA.DIST ( x, Alpha, Beta, TRUE ) equals Probability. Probability must be strictly between 0 and 1, Alpha and Beta must be positive, A must be less than B, and the result lies between A and B; A and B default to 0 and 1.",
&["BETA.INV ( 0.5, 3.51, 4.02 )", "BETA.INV ( 0.75, 3.51, 4.02, 0, 10 )"],
),
spec(
"CHISQ.DIST",
FunctionCategory::Statistical,
3,
3,
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
ReturnType::Decimal,
standard(false),
"Chi-squared distribution with Deg_freedom degrees of freedom. Cumulative TRUE returns the left-tailed cumulative distribution, FALSE the probability density. Negative X is an error and a non-integer Deg_freedom is truncated.",
&["CHISQ.DIST ( 2.5, 10, TRUE )", "CHISQ.DIST ( 2.5, 10, FALSE )"],
),
spec(
"CHISQ.DIST.RT",
FunctionCategory::Statistical,
2,
2,
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Probability in the right tail of the chi-squared distribution with Deg_freedom degrees of freedom, used to compare observed and expected values in a chi-squared test. A non-integer Deg_freedom is truncated.",
&["CHISQ.DIST.RT ( 2.5, 10 )"],
),
spec(
"CHISQ.INV",
FunctionCategory::Statistical,
2,
2,
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Inverse of the left-tailed chi-squared cumulative distribution: returns x such that CHISQ.DIST ( x, Deg_freedom, TRUE ) equals Probability. Probability must be at least 0 and less than 1; a non-integer Deg_freedom is rounded.",
&["CHISQ.INV ( 0.95, 10 )"],
),
spec(
"CHISQ.INV.RT",
FunctionCategory::Statistical,
2,
2,
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Inverse of the right-tailed chi-squared probability: returns x such that CHISQ.DIST.RT ( x, Deg_freedom ) equals Probability. Probability must be greater than 0 and at most 1; a non-integer Deg_freedom is rounded and the iterative search reports an error if it does not converge.",
&["CHISQ.INV.RT ( 0.05, 10 )"],
),
spec(
"COMBIN",
FunctionCategory::Statistical,
2,
2,
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Number of unordered combinations of Number_chosen items drawn without repetition from Number items. Numeric arguments are truncated to integers, and Number must be at least Number_chosen.",
&["COMBIN ( 8, 3 )"],
),
spec(
"COMBINA",
FunctionCategory::Statistical,
2,
2,
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Integer,
standard(false),
"Number of combinations with repetition of Number_chosen items drawn from Number items. Non-integer arguments are truncated (the remarks document rounding), both must be non-negative, and Number must be at least Number_chosen.",
&["COMBINA ( 8, 3 )"],
),
spec(
"CONFIDENCE.NORM",
FunctionCategory::Statistical,
3,
3,
&[required("Alpha", ParamKind::Number), required("Standard_dev", ParamKind::Number), required("Size", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Half-width around the sample mean for a normal-distribution confidence interval. Alpha \
is the significance level (0.05 gives a 95% interval), Standard_dev is the known \
population standard deviation and Size is the sample size.",
&["CONFIDENCE.NORM ( 0.05, 2.5, 50 )"],
),
spec(
"CONFIDENCE.T",
FunctionCategory::Statistical,
3,
3,
&[required("Alpha", ParamKind::Number), required("Standard_dev", ParamKind::Number), required("Size", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Half-width around the sample mean when the population standard deviation is unknown, \
using Student's t with Size - 1 degrees of freedom. Alpha is the significance level and \
Standard_dev is the sample standard deviation.",
&["CONFIDENCE.T ( 0.05, 2.5, 50 )"],
),
spec(
"EXPON.DIST",
FunctionCategory::Statistical,
3,
3,
&[required("X", ParamKind::Number), required("Lambda", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
ReturnType::Decimal,
standard(false),
"Exponential distribution with rate Lambda. Cumulative TRUE returns the cumulative distribution, FALSE the probability density; X must be non-negative and Lambda must be positive. Commonly used to model the time between events.",
&["EXPON.DIST ( 0.2, 10, TRUE )", "EXPON.DIST ( 0.2, 10, FALSE )"],
),
spec(
"GEOMEAN",
FunctionCategory::Statistical,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Decimal,
standard(false),
"Geometric mean of the non-blank, positive values in a numeric column. Internally equivalent to GEOMEANX; blank and non-positive values do not contribute a valid term.",
&["GEOMEAN ( Sales[Amount] )"],
),
spec(
"GEOMEANX",
FunctionCategory::Statistical,
2,
2,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Table, ParamKind::Expression])],
ReturnType::Decimal,
standard(true),
"Evaluates the expression once per row of the table and returns the geometric mean of the non-blank, positive results. The expression runs in row context, so a measure reference triggers context transition.",
&["GEOMEANX ( Sales, Sales[Amount] )"],
),
spec(
"LINEST",
FunctionCategory::Statistical,
2,
usize::MAX,
&[required("ColumnY", ParamKind::Column), required("ColumnX", ParamKind::Column), optional("Const", ParamKind::Boolean)],
&[overload(&[ParamKind::Column, ParamKind::Column]), variadic(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, true),
"Least-squares straight-line fit of ColumnY against one or more ColumnX columns, returned as a one-row table with a slope per X column, the intercept, their standard errors, the coefficient of determination, the standard error, the F statistic, degrees of freedom and the regression/residual sums of squares. All column references must come from the same table; a trailing FALSE forces the intercept to 0.",
&["LINEST ( Sales[Amount], Sales[Quantity] )", "LINEST ( Sales[Amount], Sales[Quantity], TRUE )"],
),
spec(
"LINESTX",
FunctionCategory::Statistical,
3,
usize::MAX,
&[
required("Table", ParamKind::Table),
required("ExpressionY", ParamKind::Expression),
required("ExpressionX", ParamKind::Expression),
optional("Const", ParamKind::Boolean),
],
&[
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Expression]),
variadic(&[ParamKind::Table, ParamKind::Expression, ParamKind::Expression, ParamKind::Any]),
],
ReturnType::Table,
FunctionFlags::new(true, false, false, false, true),
"Evaluates the y and x expressions row by row and returns the same least-squares regression table as LINEST: one slope per x expression, intercept, standard errors, coefficient of determination, standard error, F statistic, degrees of freedom and regression/residual sums of squares. A trailing FALSE forces the intercept to 0.",
&["LINESTX ( Sales, Sales[Amount], Sales[Quantity] )", "LINESTX ( Sales, Sales[Amount], Sales[Quantity], TRUE )"],
),
spec(
"MEDIAN",
FunctionCategory::Statistical,
1,
1,
&[required("Column", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Variant,
standard(false),
"50th percentile (median) of the non-blank numeric values in a column. Logical values, dates and text are not supported. Returns BLANK when no row has a non-blank numeric value; internally equivalent to MEDIANX, which unlike MEDIAN does not ignore blank results.",
&["MEDIAN ( Sales[Amount] )"],
),
spec(
"MEDIANX",
FunctionCategory::Statistical,
2,
2,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Table, ParamKind::Expression])],
ReturnType::Variant,
standard(true),
"Evaluates the expression once per row and returns the median of the results. Unlike MEDIAN, blank results returned by the expression are considered; the result is BLANK when no row returns a non-blank value. Integer results make the return type Variant (Integer without ties, Decimal with ties).",
&["MEDIANX ( Sales, Sales[Amount] )"],
),
spec(
"NORM.DIST",
FunctionCategory::Statistical,
4,
4,
&[
required("X", ParamKind::Number),
required("Mean", ParamKind::Number),
required("Standard_dev", ParamKind::Number),
required("Cumulative", ParamKind::Logical),
],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
ReturnType::Decimal,
standard(false),
"Normal distribution for the given Mean and Standard_dev. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function; Standard_dev must be positive.",
&["NORM.DIST ( 45, 40, 2, TRUE )", "NORM.DIST ( 45, 40, 2, FALSE )"],
),
spec(
"NORM.INV",
FunctionCategory::Statistical,
3,
3,
&[required("Probability", ParamKind::Number), required("Mean", ParamKind::Number), required("Standard_dev", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"The x for which the normal cumulative probability equals Probability, given Mean and Standard_dev. Probability must lie in (0, 1) and Standard_dev must be positive.",
&["NORM.INV ( 0.95, 40, 1.5 )"],
),
spec(
"NORM.S.DIST",
FunctionCategory::Statistical,
2,
2,
&[required("Z", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
&[overload(&[ParamKind::Number, ParamKind::Logical])],
ReturnType::Decimal,
standard(false),
"Standard normal distribution (mean 0, standard deviation 1). Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function.",
&["NORM.S.DIST ( 1.96, TRUE )", "NORM.S.DIST ( 1.96, FALSE )"],
),
spec(
"NORM.S.INV",
FunctionCategory::Statistical,
1,
1,
&[required("Probability", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"The x for which the standard normal cumulative probability equals Probability (mean 0, standard deviation 1). Probability must lie strictly between 0 and 1.",
&["NORM.S.INV ( 0.975 )"],
),
spec(
"PERCENTILE.EXC",
FunctionCategory::Statistical,
2,
2,
&[required("Column", ParamKind::Column), required("K", ParamKind::Number)],
&[overload(&[ParamKind::Column, ParamKind::Number])],
ReturnType::Variant,
standard(false),
"Exclusive k-th percentile of the non-blank values in a column. K must lie in [1/(n+1), 1-1/(n+1)], where n is the number of valid values; K outside that interval is an error. Blanks in the column are ignored, unlike the blank results considered by PERCENTILEX.EXC.",
&["PERCENTILE.EXC ( Sales[Amount], 0.9 )"],
),
spec(
"PERCENTILE.INC",
FunctionCategory::Statistical,
2,
2,
&[required("Column", ParamKind::Column), required("K", ParamKind::Number)],
&[overload(&[ParamKind::Column, ParamKind::Number])],
ReturnType::Variant,
standard(false),
"Inclusive k-th percentile of the non-blank values in a column, where K lies in [0, 1]. Blanks in the column are ignored, unlike the blank results considered by PERCENTILEX.INC.",
&["PERCENTILE.INC ( Sales[Amount], 0.9 )"],
),
spec(
"PERCENTILEX.EXC",
FunctionCategory::Statistical,
3,
3,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), required("K", ParamKind::Number)],
&[overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Number])],
ReturnType::Variant,
standard(true),
"Exclusive k-th percentile of the values returned by the expression, evaluated row by row. K must lie in [1/(n+1), 1-1/(n+1)]. Unlike PERCENTILE.EXC, blank values returned by the expression are considered.",
&["PERCENTILEX.EXC ( Sales, Sales[Amount], 0.9 )"],
),
spec(
"PERCENTILEX.INC",
FunctionCategory::Statistical,
3,
3,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), required("K", ParamKind::Number)],
&[overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Number])],
ReturnType::Variant,
standard(true),
"Inclusive k-th percentile of the values returned by the expression, evaluated row by row, where K lies in [0, 1]. Unlike PERCENTILE.INC, blank values returned by the expression are considered.",
&["PERCENTILEX.INC ( Sales, Sales[Amount], 0.9 )"],
),
spec(
"PERMUT",
FunctionCategory::Statistical,
2,
2,
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Number of ordered permutations of Number_chosen objects selected from Number objects, where order matters. Both arguments are truncated to integers; Number must be positive, Number_chosen non-negative and Number at least Number_chosen.",
&["PERMUT ( 8, 3 )"],
),
spec(
"POISSON.DIST",
FunctionCategory::Statistical,
3,
3,
&[required("X", ParamKind::Number), required("Mean", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
ReturnType::Decimal,
standard(false),
"Poisson distribution with the given Mean. Cumulative TRUE returns the probability of at most X events, FALSE the probability mass of exactly X events; a non-integer X is truncated and X must be non-negative.",
&["POISSON.DIST ( 2, 5, TRUE )", "POISSON.DIST ( 2, 5, FALSE )"],
),
spec(
"RANK.EQ",
FunctionCategory::Statistical,
2,
3,
&[required("Value", ParamKind::Scalar), required("ColumnName", ParamKind::Column), optional("Order", ParamKind::Scalar)],
&[overload(&[ParamKind::Scalar, ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Column, ParamKind::Scalar])],
ReturnType::Integer,
standard(false),
"Rank of Value among the numbers in ColumnName, with ties sharing the top rank. Order 0/FALSE/DESC ranks descending (the default) and 1/TRUE/ASC ranks ascending. Equivalent to a RANKX call over SELECTCOLUMNS rather than pure syntax sugar.",
&["RANK.EQ ( 42, Sales[Quantity] )", "RANK.EQ ( 42, Sales[Quantity], 1 )"],
),
spec(
"RANKX",
FunctionCategory::Statistical,
2,
5,
&[
required("Table", ParamKind::Table),
required("Expression", ParamKind::Expression),
optional("Value", ParamKind::Scalar),
optional("Order", ParamKind::Scalar),
optional("Ties", ParamKind::Scalar),
],
&[
overload(&[ParamKind::Table, ParamKind::Expression]),
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar]),
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar, ParamKind::Scalar]),
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar, ParamKind::Scalar, ParamKind::Scalar]),
],
ReturnType::Integer,
standard(true),
"Rank of Value (or of Expression when Value is omitted) among the values Expression returns for every row of Table. Order defaults to descending and Ties defaults to Skip; Dense gives tied elements one shared rank without gaps. Expression runs in row context. Decimal inputs can rank unexpectedly because of floating-point storage, so ROUND or a Currency type is safer.",
&["RANKX ( Sales, Sales[Amount] )", "RANKX ( Sales, Sales[Amount], 42, 0, Dense )"],
),
spec(
"SAMPLE",
FunctionCategory::Statistical,
3,
usize::MAX,
&[
required("Size", ParamKind::Number),
required("Table", ParamKind::Table),
required("OrderBy", ParamKind::Expression),
optional("Order", ParamKind::Scalar),
],
&[variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Expression])],
ReturnType::Table,
standard(true),
"Deterministic sample of Size rows from Table, ordered by one or more OrderBy expressions with optional Order values. The result is fixed: it includes the first and final rows plus the rows spaced evenly between them; Size 0 or less returns an empty table. Group the input by the sort column to avoid duplicate rows.",
&["SAMPLE ( 10, Sales, Sales[Amount] )", "SAMPLE ( 10, Sales, Sales[Amount], 0 )"],
),
spec(
"STDEV.P",
FunctionCategory::Statistical,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Decimal,
standard(false),
"Standard deviation of an entire population in a numeric column, ignoring blanks, logical values and text. Internally equivalent to STDEVX.P; use STDEV.S for a sample.",
&["STDEV.P ( Sales[Amount] )"],
),
spec(
"STDEV.S",
FunctionCategory::Statistical,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Decimal,
standard(false),
"Sample standard deviation of a numeric column, ignoring blanks, logical values and text. Internally equivalent to STDEVX.S; use STDEV.P for a complete population.",
&["STDEV.S ( Sales[Amount] )"],
),
spec(
"STDEVX.P",
FunctionCategory::Statistical,
2,
2,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Table, ParamKind::Expression])],
ReturnType::Decimal,
standard(true),
"Standard deviation of an entire population, computed from the expression evaluated once per row of the table. The expression runs in row context.",
&["STDEVX.P ( Sales, Sales[Amount] )"],
),
spec(
"STDEVX.S",
FunctionCategory::Statistical,
2,
2,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Table, ParamKind::Expression])],
ReturnType::Decimal,
standard(true),
"Sample standard deviation computed from the expression evaluated once per row of the table. The expression runs in row context.",
&["STDEVX.S ( Sales, Sales[Amount] )"],
),
spec(
"T.DIST",
FunctionCategory::Statistical,
3,
3,
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
ReturnType::Decimal,
standard(false),
"Student's left-tailed t distribution with Deg_freedom degrees of freedom. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density; Deg_freedom cannot be negative.",
&["T.DIST ( 2, 10, TRUE )", "T.DIST ( 2, 10, FALSE )"],
),
spec(
"T.DIST.2T",
FunctionCategory::Statistical,
2,
2,
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Two-tailed Student's t distribution with Deg_freedom degrees of freedom. Neither argument can be negative.",
&["T.DIST.2T ( 2, 10 )"],
),
spec(
"T.DIST.RT",
FunctionCategory::Statistical,
2,
2,
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Right-tailed Student's t distribution with Deg_freedom degrees of freedom. Deg_freedom cannot be negative.",
&["T.DIST.RT ( 2, 10 )"],
),
spec(
"T.INV",
FunctionCategory::Statistical,
2,
2,
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Solves for the t value whose cumulative probability equals Probability, on the left tail of Student's t. Probability must lie between 0 and 1 and Deg_freedom cannot be negative.",
&["T.INV ( 0.95, 10 )"],
),
spec(
"T.INV.2T",
FunctionCategory::Statistical,
2,
2,
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number])],
ReturnType::Decimal,
standard(false),
"Solves for the t value whose two-tailed probability equals Probability. Neither argument can be negative.",
&["T.INV.2T ( 0.05, 10 )"],
),
spec(
"VAR.P",
FunctionCategory::Statistical,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Decimal,
standard(false),
"Variance of an entire population in a numeric column, ignoring blanks, logical values and text. Internally equivalent to VARX.P; use VAR.S for a sample.",
&["VAR.P ( Sales[Amount] )"],
),
spec(
"VAR.S",
FunctionCategory::Statistical,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Decimal,
standard(false),
"Sample variance of a numeric column, ignoring blanks, logical values and text. Internally equivalent to VARX.S; use VAR.P for a complete population.",
&["VAR.S ( Sales[Amount] )"],
),
spec(
"VARX.P",
FunctionCategory::Statistical,
2,
2,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Table, ParamKind::Expression])],
ReturnType::Decimal,
standard(true),
"Variance of an entire population, computed from the expression evaluated once per row of the table. The expression runs in row context.",
&["VARX.P ( Sales, Sales[Amount] )"],
),
spec(
"VARX.S",
FunctionCategory::Statistical,
2,
2,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Table, ParamKind::Expression])],
ReturnType::Decimal,
standard(true),
"Sample variance computed from the expression evaluated once per row of the table. The expression runs in row context.",
&["VARX.S ( Sales, Sales[Amount] )"],
),
];
@@ -0,0 +1,641 @@
//! Table manipulation functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! The category holds four kinds of functions:
//!
//! - table constructors and projections (`DATATABLE`, `ROW`, `ADDCOLUMNS`, `SELECTCOLUMNS`,
//! `SUMMARIZE`, `SUMMARIZECOLUMNS`, `GROUPBY`);
//! - relational operations (`CROSSJOIN`, `UNION`, `EXCEPT`, `INTERSECT`, the natural joins and
//! `SUBSTITUTEWITHINDEX`);
//! - companion functions that are only valid as arguments of those operations (`CURRENTGROUP`,
//! `IGNORE`, `NONVISUAL`, `NATURALJOINUSAGE`, `ROLLUP`, `ROLLUPGROUP`,
//! `ROLLUPADDISSUBTOTAL`, `ROLLUPISSUBTOTAL`);
//! - row selection and value helpers (`DISTINCT`, `VALUES`, `FILTERS`, `TOPN`, `TOPNSKIP`,
//! `GENERATESERIES`, `DETAILROWS`, `TREATAS`, `SAMPLEAXISWITHLOCALMINMAX`,
//! `TOPNPERLEVEL`).
//!
//! The companion functions are catalogued because the parser accepts them, but several do not
//! return a value on their own: they are syntax markers inside `SUMMARIZE`,
//! `SUMMARIZECOLUMNS` or `ADDMISSINGITEMS`, so their return type is [`ReturnType::Blank`].
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
/// Available to every host, with the usual DirectQuery restrictions.
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
/// Iterators evaluate an expression once per row of the first table argument.
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
/// No Excel version listed by dax.guide supports the function.
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
/// Power BI-only extension functions: engine extensions that DirectQuery cannot evaluate.
const EXTENSION: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"ADDCOLUMNS",
FunctionCategory::TableManipulation,
3,
usize::MAX,
&[required("Table", ParamKind::Table), required("Name", ParamKind::Text), required("Expression", ParamKind::Expression)],
&[variadic(&[ParamKind::Table, ParamKind::Text, ParamKind::Expression])],
ReturnType::Table,
ITERATOR,
"Returns the input table with new columns added. Each expression is evaluated in the \
row context of the table, so the expressions are repeatable in `Name, Expression` \
pairs. The added columns keep the data lineage of a simple column reference for \
NATURALINNERJOIN/NATURALLEFTOUTERJOIN but not for context transition.",
&[
"ADDCOLUMNS ( Sales, \"Margin\", Sales[Amount] - Sales[Cost] )",
"ADDCOLUMNS ( Product, \"Brand\", Product[Brand], \"Price\", Product[List Price] )",
],
),
spec(
"ADDMISSINGITEMS",
FunctionCategory::TableManipulation,
1,
usize::MAX,
&[
optional("ShowAll_ColumnName", ParamKind::Column),
required("Table", ParamKind::Table),
optional("GroupBy_ColumnName", ParamKind::Any),
optional("FilterTable", ParamKind::Table),
],
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Any])],
ReturnType::Table,
STANDARD,
"Adds back the rows of a SUMMARIZECOLUMNS result that were removed because every \
measure was blank. The optional leading columns list which columns must show all \
items; the table argument is the SUMMARIZECOLUMNS result, followed by optional \
group-by columns (possibly ROLLUPGROUP/ROLLUPADDISSUBTOTAL calls) and filters. \
ROLLUPISSUBTOTAL marks the subtotal columns.",
&["ADDMISSINGITEMS ( Sales[Region], SUMMARIZECOLUMNS ( Sales[Region], \"Amount\", SUM ( Sales[Amount] ) ), Sales[Region] )"],
),
spec(
"CROSSJOIN",
FunctionCategory::TableManipulation,
1,
usize::MAX,
&[required("Table", ParamKind::Table)],
&[variadic(&[ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Returns the Cartesian product of the table arguments. The result has the product of \
the row counts and the sum of the column counts; column names must be different in \
every argument or the function raises an error.",
&["CROSSJOIN ( Product, Store )", "CROSSJOIN ( Product, Store, 'Date' )"],
),
spec(
"CURRENTGROUP",
FunctionCategory::TableManipulation,
0,
0,
&[],
&[overload(&[])],
ReturnType::Table,
STANDARD,
"Returns the subset of rows of the GROUPBY input table that belong to the current \
group. It takes no arguments and is only valid as the table argument of an \
aggregation iterator inside GROUPBY, such as SUMX or COUNTX.",
&["GROUPBY ( Sales, Sales[Region], \"Amount\", SUMX ( CURRENTGROUP (), Sales[Amount] ) )"],
),
spec(
"DATATABLE",
FunctionCategory::TableManipulation,
3,
usize::MAX,
&[required("Name", ParamKind::Text), required("DataType", ParamKind::Text), required("Data", ParamKind::Any)],
&[variadic(&[ParamKind::Text, ParamKind::Text, ParamKind::Any])],
ReturnType::Table,
STANDARD,
"Returns a table whose columns and rows are declared inline. Column names and data type \
names alternate, followed by a single table constructor with the data. Data type names \
are BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64 and \
STRING/TEXT; unlike the table constructor, DATATABLE requires literal values.",
&[
"DATATABLE ( \"Name\", STRING, { { \"Small\", 1 }, { \"Medium\", 2 } } )",
"DATATABLE ( \"Name\", STRING, \"Ordinal\", INTEGER, { { \"Small\", 1 }, { \"Large\", 3 } } )",
],
),
spec(
"DETAILROWS",
FunctionCategory::TableManipulation,
1,
1,
&[required("Measure", ParamKind::Reference)],
&[overload(&[ParamKind::Reference])],
ReturnType::Table,
STANDARD,
"Returns the table produced by the DetailRows expression defined on a measure. When the \
measure has no DetailRows expression, the entire table the measure belongs to is \
returned. Context transition is not applied by the engine; wrap the call in \
CALCULATETABLE inside a row context when transition is intended.",
&["DETAILROWS ( [Sales Amount] )"],
),
spec(
"DISTINCT",
FunctionCategory::TableManipulation,
1,
1,
&[required("ColumnNameOrTableExpr", ParamKind::Reference)],
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Returns the distinct values of a column, or the distinct rows of a table expression. \
Unlike VALUES, a column argument does not add the blank row generated by an invalid \
relationship.",
&["DISTINCT ( Sales[Region] )", "DISTINCT ( Sales )"],
),
spec(
"EXCEPT",
FunctionCategory::TableManipulation,
2,
2,
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
&[overload(&[ParamKind::Table, ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Returns the rows of the left table that do not appear in the right table. A row present \
in both tables is removed together with its duplicates; columns are matched by position \
with strict comparison and the result keeps the left table's column names and lineage.",
&["EXCEPT ( Sales, SalesArchive )"],
),
spec(
"FILTERS",
FunctionCategory::TableManipulation,
1,
1,
&[required("ColumnName", ParamKind::Column)],
&[overload(&[ParamKind::Column])],
ReturnType::Table,
STANDARD,
"Returns the filter values applied directly to a column, as a single-column table. The \
column argument must be a column reference; the result can include the blank row \
generated by an invalid relationship.",
&["FILTERS ( Store[Continent] )", "FILTERS ( 'Date'[Calendar Year] )"],
),
spec(
"GENERATE",
FunctionCategory::TableManipulation,
2,
2,
&[required("Table1", ParamKind::Table), required("Table2", ParamKind::Table)],
&[overload(&[ParamKind::Table, ParamKind::Table])],
ReturnType::Table,
ITERATOR,
"Evaluates the second table expression for every row of the first table and returns the \
union of those results with the corresponding first-table columns. Rows of the first \
table whose second expression is empty are dropped, unlike GENERATEALL.",
&["GENERATE ( Product, RELATEDTABLE ( Sales ) )"],
),
spec(
"GENERATEALL",
FunctionCategory::TableManipulation,
2,
2,
&[required("Table1", ParamKind::Table), required("Table2", ParamKind::Table)],
&[overload(&[ParamKind::Table, ParamKind::Table])],
ReturnType::Table,
ITERATOR,
"Evaluates the second table expression for every row of the first table and keeps the \
first-table row even when that expression is empty, filling the second table's columns \
with blanks. Column names must be different in both arguments.",
&["GENERATEALL ( Product, RELATEDTABLE ( Sales ) )"],
),
spec(
"GENERATESERIES",
FunctionCategory::TableManipulation,
2,
3,
&[required("StartValue", ParamKind::Number), required("EndValue", ParamKind::Number), optional("IncrementValue", ParamKind::Number)],
&[overload(&[ParamKind::Number, ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
ReturnType::Table,
STANDARD,
"Returns a single-column table named Value holding an arithmetic series from StartValue \
to EndValue. IncrementValue must be positive and defaults to 1; the series stops at the \
last value less than or equal to EndValue, and EndValue below StartValue yields an \
empty table.",
&["GENERATESERIES ( 1, 10, 2 )", "GENERATESERIES ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )"],
),
spec(
"GROUPBY",
FunctionCategory::TableManipulation,
1,
usize::MAX,
&[
required("Table", ParamKind::Table),
optional("GroupBy_ColumnName", ParamKind::Column),
optional("Name", ParamKind::Text),
optional("Expression", ParamKind::Expression),
],
&[
overload(&[ParamKind::Table]),
overload(&[ParamKind::Table, ParamKind::Column]),
variadic(&[ParamKind::Table, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Table,
STANDARD,
"Groups the input table by the given columns and adds expression columns evaluated per \
group. Expressions added by GROUPBY must aggregate CURRENTGROUP() and cannot use \
CALCULATE; use SUMMARIZE when the added columns aggregate base-table columns.",
&["GROUPBY ( Sales, Sales[Region], \"Amount\", SUMX ( CURRENTGROUP (), Sales[Amount] ) )", "GROUPBY ( Customer, Customer[Country] )"],
),
spec(
"IGNORE",
FunctionCategory::TableManipulation,
1,
1,
&[required("Measure_Expression", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Blank,
STANDARD,
"Marks a SUMMARIZECOLUMNS expression so that it is excluded when deciding whether a row \
is blank. Rows are kept as long as another expression without IGNORE returns a value; \
the function itself returns no value.",
&["SUMMARIZECOLUMNS ( Sales[Region], IGNORE ( [Sales Amount] ) )"],
),
spec(
"INTERSECT",
FunctionCategory::TableManipulation,
2,
2,
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
&[overload(&[ParamKind::Table, ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Returns the rows of the left table that also appear in the right table, keeping \
duplicates from the left table. Columns are matched by position without type coercion; \
the operation is not commutative and the result keeps the left table's column names and \
lineage.",
&["INTERSECT ( Sales, SalesArchive )"],
),
spec(
"NATURALINNERJOIN",
FunctionCategory::TableManipulation,
2,
2,
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
&[overload(&[ParamKind::Table, ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Joins two tables on all columns they have in common (including columns of their \
expanded tables) and returns the matching rows. Joined columns must have the same name, \
data type and lineage; comparison is strict, with no type coercion.",
&["NATURALINNERJOIN ( Sales, Product )"],
),
spec(
"NATURALJOINUSAGE",
FunctionCategory::TableManipulation,
1,
1,
&[required("Expression", ParamKind::Any)],
&[overload(&[ParamKind::Any])],
ReturnType::Table,
ENGINE_ONLY,
"Adds a table as a natural join to the filter context. It is only valid as a value \
filter of SUMMARIZECOLUMNS and is used mostly in queries sent to composite models; \
dax.guide lists no Excel support and Microsoft documentation is not available.",
&["SUMMARIZECOLUMNS ( Sales[Region], NATURALJOINUSAGE ( Product ) )"],
),
spec(
"NATURALLEFTOUTERJOIN",
FunctionCategory::TableManipulation,
2,
2,
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
&[overload(&[ParamKind::Table, ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Joins two tables on all columns they have in common and returns every row of the left \
table, with blanks where the right table has no match. Joined columns must share name, \
data type and lineage, and comparison does not coerce types.",
&["NATURALLEFTOUTERJOIN ( Sales, Product )"],
),
spec(
"NONVISUAL",
FunctionCategory::TableManipulation,
1,
1,
&[required("Expression", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Marks a SUMMARIZECOLUMNS value filter as non-visual: the filter still restricts the \
grouping columns but does not affect measure values, so measures that use \
ALLSELECTED can return the non-visual totals.",
&["SUMMARIZECOLUMNS ( 'Date'[Calendar Year], NONVISUAL ( TREATAS ( { \"CY 2008\" }, 'Date'[Calendar Year] ) ), \"Amount\", [Sales Amount] )"],
),
spec(
"ROLLUP",
FunctionCategory::TableManipulation,
1,
usize::MAX,
&[required("GroupBy_ColumnName", ParamKind::Column)],
&[variadic(&[ParamKind::Any])],
ReturnType::Blank,
STANDARD,
"Identifies the SUMMARIZE group-by columns that also produce subtotal rows. The \
arguments must be qualified column names, not expressions, and are only valid inside \
SUMMARIZE; the function itself returns no value.",
&["SUMMARIZE ( Sales, ROLLUP ( Sales[Country], Sales[City] ), \"Amount\", SUM ( Sales[Amount] ) )"],
),
spec(
"ROLLUPADDISSUBTOTAL",
FunctionCategory::TableManipulation,
2,
usize::MAX,
&[
optional("GrandtotalFilter", ParamKind::Table),
required("GroupBy_ColumnName", ParamKind::Column),
required("Name", ParamKind::Text),
optional("GroupLevelFilter", ParamKind::Table),
],
&[variadic(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Blank,
STANDARD,
"Identifies the SUMMARIZECOLUMNS group-by columns that produce subtotals and adds a \
Boolean column per pair indicating whether the row is a subtotal. It accepts an \
optional grand-total filter before the pairs and an optional per-level filter after \
each pair; it is only valid inside SUMMARIZECOLUMNS and returns no value.",
&["SUMMARIZECOLUMNS ( ROLLUPADDISSUBTOTAL ( Sales[Country], \"IsSubtotal Country\" ), \"Amount\", SUM ( Sales[Amount] ) )"],
),
spec(
"ROLLUPGROUP",
FunctionCategory::TableManipulation,
1,
usize::MAX,
&[required("GroupBy_ColumnName", ParamKind::Column)],
&[variadic(&[ParamKind::Column])],
ReturnType::Blank,
STANDARD,
"Identifies a group of SUMMARIZE or SUMMARIZECOLUMNS columns that produce subtotals \
together. Inside ROLLUP it suppresses the partial subtotals that ROLLUP would \
otherwise add; the function itself returns no value.",
&["SUMMARIZE ( Sales, ROLLUPGROUP ( Sales[Country], Sales[City] ), \"Amount\", SUM ( Sales[Amount] ) )"],
),
spec(
"ROLLUPISSUBTOTAL",
FunctionCategory::TableManipulation,
2,
usize::MAX,
&[
optional("GrandtotalFilter", ParamKind::Table),
required("GroupBy_ColumnName", ParamKind::Column),
required("IsSubtotal_ColumnName", ParamKind::Text),
optional("GroupLevelFilter", ParamKind::Table),
],
&[variadic(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Blank,
STANDARD,
"Pairs the subtotal columns created by ROLLUPADDISSUBTOTAL with their group-by columns \
so that ADDMISSINGITEMS can add the missing subtotal rows. It is only valid inside \
ADDMISSINGITEMS and returns no value.",
&[
"ADDMISSINGITEMS ( Sales[Country], SUMMARIZECOLUMNS ( ROLLUPADDISSUBTOTAL ( Sales[Country], \"IsSubtotal\" ), \"Amount\", SUM ( Sales[Amount] ) ), ROLLUPISSUBTOTAL ( Sales[Country], [IsSubtotal] ) )",
],
),
spec(
"ROW",
FunctionCategory::TableManipulation,
2,
usize::MAX,
&[required("Name", ParamKind::Text), required("Expression", ParamKind::Any)],
&[variadic(&[ParamKind::Text, ParamKind::Any])],
ReturnType::Table,
STANDARD,
"Returns a single-row table with the named columns. Arguments come in `Name, \
Expression` pairs; column references used as expressions lose their data lineage rather \
than keeping it.",
&["ROW ( \"Product\", \"Bike\", \"Price\", 1500 )", "ROW ( \"Value\", 1 )"],
),
spec(
"SAMPLEAXISWITHLOCALMINMAX",
FunctionCategory::TableManipulation,
5,
usize::MAX,
&[
required("Size", ParamKind::Number),
required("Table", ParamKind::Table),
required("Axis", ParamKind::Column),
required("Measure", ParamKind::Expression),
required("MinResolution", ParamKind::Number),
optional("DynamicSeries", ParamKind::Column),
optional("DynamicSeriesSelectionCriteria", ParamKind::Text),
optional("DynamicSeriesSelectionOrder", ParamKind::Boolean),
optional("MaxResolution", ParamKind::Number),
optional("MaxDynamicSeries", ParamKind::Number),
optional("MaxIterations", ParamKind::Number),
],
&[variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Any, ParamKind::Number])],
ReturnType::Table,
ENGINE_ONLY,
"Returns a subset of the input table obtained by binning the numeric or date axis into \
equal-sized bins and preserving the local minimum and maximum of each measure per \
series. Power BI uses it to reduce the points of line charts with a continuous axis; \
dax.guide lists no Excel support and Microsoft documentation is not available.",
&["SAMPLEAXISWITHLOCALMINMAX ( 100, Sales, Sales[Order Date], Sales[Amount], 10 )"],
),
spec(
"SELECTCOLUMNS",
FunctionCategory::TableManipulation,
1,
usize::MAX,
&[required("Table", ParamKind::Table), optional("Name", ParamKind::Text), optional("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Any])],
ReturnType::Table,
ITERATOR,
"Projects the input to one column per `Name, Expression` pair, keeping the same row \
count; each expression is evaluated in row context. Unlike ADDCOLUMNS it starts from an \
empty table; the name may be omitted when the expression is a simple column reference, \
and simple references keep their data lineage.",
&[
"SELECTCOLUMNS ( Sales, \"Amount\", Sales[Amount] )",
"SELECTCOLUMNS ( Product, \"Brand\", Product[Brand], \"Category\", Product[Category] )",
],
),
spec(
"SUBSTITUTEWITHINDEX",
FunctionCategory::TableManipulation,
4,
usize::MAX,
&[
required("Table", ParamKind::Table),
required("Name", ParamKind::Text),
required("SemiJoinIndexTable", ParamKind::Table),
required("Expression", ParamKind::Expression),
optional("Order", ParamKind::Number),
],
&[variadic(&[ParamKind::Table, ParamKind::Text, ParamKind::Table, ParamKind::Expression])],
ReturnType::Table,
ITERATOR,
"Semijoins two tables and replaces the common columns with a zero-based index column. \
The index follows the row order obtained by sorting the second table with the supplied \
order expressions; matching uses the same lineage rules as the natural joins and raises \
an error when no column matches.",
&["SUBSTITUTEWITHINDEX ( Sales, \"ProductIndex\", DISTINCT ( Sales[ProductKey] ), Sales[ProductKey] )"],
),
spec(
"SUMMARIZE",
FunctionCategory::TableManipulation,
1,
usize::MAX,
&[
required("Table", ParamKind::Table),
optional("GroupBy_ColumnName", ParamKind::Reference),
optional("Name", ParamKind::Text),
optional("Expression", ParamKind::Expression),
],
&[
overload(&[ParamKind::Table]),
overload(&[ParamKind::Table, ParamKind::Reference]),
variadic(&[ParamKind::Table, ParamKind::Reference, ParamKind::Any]),
],
ReturnType::Table,
STANDARD,
"Groups the input table by the given columns and optionally adds computed columns. The \
group-by arguments can be columns of the table or its related tables, or ROLLUP / \
ROLLUPGROUP calls. Adding columns with SUMMARIZE is deprecated in favour of \
SUMMARIZECOLUMNS or ADDCOLUMNS, and ROLLUP/ROLLUPGROUP columns lose their data lineage.",
&["SUMMARIZE ( Sales, Sales[Region], \"Amount\", SUM ( Sales[Amount] ) )", "SUMMARIZE ( Sales, 'Product'[Brand], 'Date'[Calendar Year] )"],
),
spec(
"SUMMARIZECOLUMNS",
FunctionCategory::TableManipulation,
0,
usize::MAX,
&[
optional("GroupBy_ColumnName", ParamKind::Any),
optional("FilterTable", ParamKind::Table),
optional("Name", ParamKind::Text),
optional("Expression", ParamKind::Expression),
],
&[overload(&[]), variadic(&[ParamKind::Any])],
ReturnType::Table,
STANDARD,
"Builds a summary table from group-by columns, filters applied only to the grouping, and \
added expression columns. A row is included only when at least one expression returns a \
non-blank value; filters accept KEEPFILTERS, REMOVEFILTERS and NONVISUAL, and group-by \
arguments accept ROLLUPGROUP and ROLLUPADDISSUBTOTAL. Since June 2024 it can run inside \
context transition, with the remaining limitations documented by Microsoft.",
&[
"SUMMARIZECOLUMNS ( Sales[Region], \"Amount\", SUM ( Sales[Amount] ) )",
"SUMMARIZECOLUMNS ( 'Product'[Brand], 'Date'[Calendar Year], \"Amount\", [Sales Amount] )",
"SUMMARIZECOLUMNS ( )",
],
),
spec(
"TOPN",
FunctionCategory::TableManipulation,
2,
usize::MAX,
&[
required("N_Value", ParamKind::Number),
required("Table", ParamKind::Table),
optional("OrderBy_Expression", ParamKind::Expression),
optional("Order", ParamKind::Number),
],
&[overload(&[ParamKind::Number, ParamKind::Table]), variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Expression])],
ReturnType::Table,
ITERATOR,
"Returns the top N rows of a table according to the order-by expressions. Order is \
0/FALSE/DESC or 1/TRUE/ASC and defaults to descending; ties at the N-th row are all \
returned, and N_Value of zero or less yields an empty table. The result has no \
guaranteed sort order.",
&["TOPN ( 10, Sales, Sales[Amount], DESC )"],
),
spec(
"TOPNPERLEVEL",
FunctionCategory::TableManipulation,
6,
6,
&[
required("Rows", ParamKind::Number),
required("Table", ParamKind::Table),
required("LevelsDefinition", ParamKind::Table),
required("NodesExpanded", ParamKind::Table),
required("LevelsBoundaries", ParamKind::Table),
required("RestartIndicatorColumnName", ParamKind::Text),
],
&[overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Table, ParamKind::Table, ParamKind::Table, ParamKind::Text])],
ReturnType::Table,
EXTENSION,
"Returns the rows to display for an expanded hierarchy, restricted to the selected nodes \
and boundaries. It is an undocumented Power BI extension that is not part of the \
Analysis Services engine and has no Excel or DirectQuery support.",
&["TOPNPERLEVEL ( 10, Sales, Levels, Expanded, Boundaries, \"Restart\" )"],
),
spec(
"TOPNSKIP",
FunctionCategory::TableManipulation,
3,
usize::MAX,
&[
required("Rows", ParamKind::Number),
required("Skip_Rows_Value", ParamKind::Number),
required("Table", ParamKind::Table),
optional("OrderBy_Expression", ParamKind::Expression),
optional("Order", ParamKind::Number),
optional("Ties", ParamKind::Text),
],
&[
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Table]),
variadic(&[ParamKind::Number, ParamKind::Number, ParamKind::Table, ParamKind::Any]),
],
ReturnType::Table,
ITERATOR,
"Retrieves Rows rows from a table after skipping Skip rows, ordered by the order-by \
expressions. Ties can be handled as Skip (ranking skips tied elements) or Dense (all \
tied elements count as one); the result has no guaranteed sort order. With a non-zero \
skip the table has to reference physical columns that carry lineage, and context \
transition cannot occur.",
&["TOPNSKIP ( 10, 20, Sales, Sales[Amount], DESC )"],
),
spec(
"TREATAS",
FunctionCategory::TableManipulation,
2,
usize::MAX,
&[required("Expression", ParamKind::Table), required("ColumnName", ParamKind::Column)],
&[variadic(&[ParamKind::Table, ParamKind::Column])],
ReturnType::Table,
STANDARD,
"Applies the data lineage of the output columns to the table returned by the first \
argument, so that its values filter the model columns as if they came from those \
columns. Only a table expression is accepted there; unused values are filtered out and \
the result can be stored in a variable.",
&["TREATAS ( { \"North America\" }, Sales[Region] )", "TREATAS ( { 2008, 2009 }, 'Date'[Calendar Year] )"],
),
spec(
"UNION",
FunctionCategory::TableManipulation,
2,
usize::MAX,
&[required("Table", ParamKind::Table), required("Table2", ParamKind::Table)],
&[variadic(&[ParamKind::Table, ParamKind::Table])],
ReturnType::Table,
STANDARD,
"Returns all rows of all table arguments, keeping duplicates. Columns are combined by \
position and the result takes its column names from the first table; differing data \
types are resolved with DAX coercion rules, and lineage is kept only where all input \
columns share it.",
&["UNION ( Sales, SalesArchive )", "UNION ( Sales, SalesArchive, SalesForecast )"],
),
spec(
"VALUES",
FunctionCategory::TableManipulation,
1,
1,
&[required("TableNameOrColumnName", ParamKind::Reference)],
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Table])],
ReturnType::Table,
STANDARD,
"With a column, returns its unique values as a single-column table, including the blank \
row produced by an invalid relationship. With a table name it returns every row of that \
table with its columns unchanged, without removing duplicates. VALUES needs a model \
table or column, so it cannot be applied to a variable.",
&["VALUES ( Sales[Region] )", "VALUES ( Store )"],
),
];
+433
View File
@@ -0,0 +1,433 @@
//! Text functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! The category splits into three kinds of functions:
//!
//! - string construction (`COMBINEVALUES`, `CONCATENATE`, `CONCATENATEX`, `LEFT`, `MID`,
//! `REPLACE`, `REPT`, `RIGHT`, `SUBSTITUTE`, `TRIM`), which return text and whose result
//! length is measured in Unicode code points;
//! - classification and conversion (`EXACT`, `FIND`, `LEN`, `LOWER`, `SEARCH`, `UNICHAR`,
//! `UNICODE`, `UPPER`), which are case- or accent-sensitive to different degrees;
//! - formatting and serialization (`FIXED`, `FORMAT`, `TOCSV`, `TOJSON`, `VALUE`), whose output
//! or parsing depends on the model locale.
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
/// Available to every host, with no documented DirectQuery restriction.
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, false);
/// Functions that DirectQuery does not support in calculated columns.
const DQ_RESTRICTED: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
/// `CONCATENATEX` is an iterator and is also restricted in DirectQuery calculated columns.
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
/// Engine-only functions: no Excel version listed by dax.guide supports them.
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"COMBINEVALUES",
FunctionCategory::Text,
3,
usize::MAX,
&[required("Delimiter", ParamKind::Text), required("Expression1", ParamKind::Any), required("Expression2", ParamKind::Any)],
&[variadic(&[ParamKind::Text, ParamKind::Any, ParamKind::Any])],
ReturnType::String,
STANDARD,
"Concatenates two or more scalar values with a delimiter and returns one text value. The \
function is designed for calculated columns that stand in for multi-column relationships \
in DirectQuery models: the engine can translate the call into an optimized join \
predicate, assuming without validating that different input combinations produce \
different output strings. Choose a delimiter that cannot occur ambiguously in the \
values, and remember that the delimiter itself is not escaped.",
&["COMBINEVALUES ( \" | \", Customer[Customer Name], Customer[Customer Code] )", "COMBINEVALUES ( \"-\", \"GridCraft\", \"2024\", \"Q1\" )"],
),
spec(
"CONCATENATE",
FunctionCategory::Text,
2,
2,
&[required("Text1", ParamKind::Text), required("Text2", ParamKind::Text)],
&[overload(&[ParamKind::Text, ParamKind::Text])],
ReturnType::String,
STANDARD,
"Joins two text values into one text value without inserting a separator. The `&` operator \
performs the same concatenation and accepts any number of operands, so CONCATENATE is \
only convenient for two. Non-text arguments are converted to text using the model's \
locale rather than the caller's culture.",
&["CONCATENATE ( \"GridCraft\", \" 2024\" )", "CONCATENATE ( Customer[Customer Name], Customer[Customer Code] )"],
),
spec(
"CONCATENATEX",
FunctionCategory::Text,
2,
usize::MAX,
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
&[
overload(&[ParamKind::Table, ParamKind::Expression]),
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text]),
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression]),
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression, ParamKind::Logical]),
variadic(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression]),
],
ReturnType::String,
ITERATOR,
"Iterates a table, evaluates the expression for every row and concatenates the results \
into a single text value using an optional delimiter. An order-by expression and an \
optional order (0/FALSE/DESC or 1/TRUE/ASC, ascending by default) sort the values; \
without them the row order is unspecified and does not reflect the source table's \
physical order. Ordering follows the model collation, while the delimiter is inserted \
verbatim.",
&[
"CONCATENATEX ( Sales, Sales[Product], \", \" )",
"CONCATENATEX ( Sales, Sales[Product], \", \", Sales[Amount] )",
"CONCATENATEX ( Sales, Sales[Product], \", \", Sales[Amount], TRUE )",
],
),
spec(
"EXACT",
FunctionCategory::Text,
2,
2,
&[required("Text1", ParamKind::Text), required("Text2", ParamKind::Text)],
&[overload(&[ParamKind::Text, ParamKind::Text])],
ReturnType::Boolean,
STANDARD,
"Compares two text values and returns TRUE when they are exactly the same, including \
case. The ordinary `=` comparison is case-insensitive, so EXACT is the way to force a \
case-sensitive and accent-sensitive test. BLANK and an empty string compare equal here.",
&["EXACT ( \"GridCraft\", \"gridcraft\" )", "EXACT ( Sales[Code], \"A-100\" )"],
),
spec(
"FIND",
FunctionCategory::Text,
2,
4,
&[
required("FindText", ParamKind::Text),
required("WithinText", ParamKind::Text),
optional("StartPosition", ParamKind::Number),
optional("NotFoundValue", ParamKind::Any),
],
&[
overload(&[ParamKind::Text, ParamKind::Text]),
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number]),
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number, ParamKind::Any]),
],
ReturnType::Integer,
STANDARD,
"Returns the 1-based position of FindText inside WithinText, beginning the search at \
StartPosition (default 1). The comparison is case-sensitive and accent-sensitive, and \
wildcards are not interpreted; use SEARCH for case-insensitive or wildcard matching. If \
the text is absent the function returns NotFoundValue when it is supplied, otherwise it \
raises an error.",
&["FIND ( \"Red\", \"GridCraft Cell S100 Red\" )", "FIND ( \"Red\", \"GridCraft Cell S100 Red\", 1, BLANK () )"],
),
spec(
"FIXED",
FunctionCategory::Text,
1,
3,
&[required("Number", ParamKind::Number), optional("Decimals", ParamKind::Number), optional("NoCommas", ParamKind::Boolean)],
&[
overload(&[ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Boolean]),
],
ReturnType::String,
DQ_RESTRICTED,
"Rounds a number to the requested number of decimals and returns it as text, grouping the \
integer part with commas unless NoCommas is TRUE. Decimals defaults to 2, and a negative \
value rounds to the left of the decimal separator. The decimal and grouping separators \
come from the model locale, not from the caller's culture.",
&["FIXED ( 384518.16, 2, FALSE )", "FIXED ( 4392768.29, 0, TRUE )", "FIXED ( 6741548.73, -2 )"],
),
spec(
"FORMAT",
FunctionCategory::Text,
2,
3,
&[required("Value", ParamKind::Any), required("Format", ParamKind::Text), optional("LocaleName", ParamKind::Text)],
&[overload(&[ParamKind::Any, ParamKind::Text]), overload(&[ParamKind::Any, ParamKind::Text, ParamKind::Text])],
ReturnType::String,
DQ_RESTRICTED,
"Formats a value as text using a Visual Basic (OLE Automation) format string or one of \
the predefined numeric and date/time format names; unknown strings are treated as a \
custom format or literal. The result is always text, and BLANK produces an empty string. \
Month and weekday names and separators follow the model locale, which the optional \
LocaleName overrides where the host supports that argument.",
&["FORMAT ( 0.742, \"Percent\" )", "FORMAT ( DATE ( 2019, 3, 28 ), \"yyyy-mm-dd\" )", "FORMAT ( 1234.567, \"$#,0.00\", \"en-US\" )"],
),
spec(
"LEFT",
FunctionCategory::Text,
1,
2,
&[required("Text", ParamKind::Text), optional("NumberOfCharacters", ParamKind::Number)],
&[overload(&[ParamKind::Text]), overload(&[ParamKind::Text, ParamKind::Number])],
ReturnType::String,
STANDARD,
"Returns the first NumberOfCharacters characters of a text value; the count defaults to 1. \
It is intended for fixed-position extraction. Characters are counted as Unicode code \
points, and no case or locale conversion is applied to the result.",
&["LEFT ( \"DAX is so cool!\", 3 )", "LEFT ( Customer[Customer Name] )"],
),
spec(
"LEN",
FunctionCategory::Text,
1,
1,
&[required("Text", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::Integer,
STANDARD,
"Character count of a text value, spaces included. Characters are Unicode code points, \
so a character outside the Basic Multilingual Plane counts as one.",
&["LEN ( \"DAX is so cool!\" )", "LEN ( Customer[Customer Name] )"],
),
spec(
"LOWER",
FunctionCategory::Text,
1,
1,
&[required("Text", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::String,
STANDARD,
"Converts every letter in a text value to lowercase and returns the result. Case mapping \
follows Unicode rules and is locale-sensitive for some scripts, such as the Turkish \
dotted and dotless I, while digits and symbols are left unchanged.",
&["LOWER ( \"DAX is SO cool!\" )", "LOWER ( Customer[CountryRegion] )"],
),
spec(
"MID",
FunctionCategory::Text,
3,
3,
&[required("Text", ParamKind::Text), required("StartPosition", ParamKind::Number), required("NumberOfCharacters", ParamKind::Number)],
&[overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Number])],
ReturnType::String,
STANDARD,
"Returns NumberOfCharacters characters from a text value starting at the 1-based \
StartPosition. If the requested length extends past the end of the text only the \
remaining characters are returned. Positions and lengths are counted in Unicode code \
points, and no case conversion is applied.",
&["MID ( \"DAX is so cool!\", 11, 4 )", "MID ( \"123-45-6789\", 8, 3 )"],
),
spec(
"REPLACE",
FunctionCategory::Text,
4,
4,
&[
required("OldText", ParamKind::Text),
required("StartPosition", ParamKind::Number),
required("NumberOfCharacters", ParamKind::Number),
required("NewText", ParamKind::Text),
],
&[overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Number, ParamKind::Text])],
ReturnType::String,
DQ_RESTRICTED,
"Replaces a fixed run of characters: NumberOfCharacters characters starting at the \
1-based StartPosition are replaced by NewText, whose length need not match the removed \
text. Because the position is explicit there is no searching, so case and locale do not \
affect the match; positions are counted in Unicode code points.",
&["REPLACE ( \"DAX is so cool!\", 11, 4, \"fantastic\" )", "REPLACE ( \"123-45-6789\", 1, 3, \"XXX\" )"],
),
spec(
"REPT",
FunctionCategory::Text,
2,
2,
&[required("Text", ParamKind::Text), required("NumberOfTimes", ParamKind::Number)],
&[overload(&[ParamKind::Text, ParamKind::Number])],
ReturnType::String,
STANDARD,
"Repeats a text value NumberOfTimes times and returns the concatenation. A count of zero \
returns an empty string, a fractional count is truncated to an integer, and the \
result may not exceed 32,767 characters or the function raises an error. The text is \
repeated verbatim, without case or locale conversion.",
&["REPT ( \"?\", 3 )", "REPT ( \"0\", 5 )"],
),
spec(
"RIGHT",
FunctionCategory::Text,
1,
2,
&[required("Text", ParamKind::Text), optional("NumberOfCharacters", ParamKind::Number)],
&[overload(&[ParamKind::Text]), overload(&[ParamKind::Text, ParamKind::Number])],
ReturnType::String,
STANDARD,
"Returns the last NumberOfCharacters characters of a text value; the count defaults to 1. \
It is intended for fixed-position extraction from the end of the text. Counting is by \
Unicode code point, and no case conversion is applied.",
&["RIGHT ( \"DAX is so cool!\", 5 )", "RIGHT ( Customer[Customer Code], 4 )"],
),
spec(
"SEARCH",
FunctionCategory::Text,
2,
4,
&[
required("FindText", ParamKind::Text),
required("WithinText", ParamKind::Text),
optional("StartPosition", ParamKind::Number),
optional("NotFoundValue", ParamKind::Any),
],
&[
overload(&[ParamKind::Text, ParamKind::Text]),
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number]),
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number, ParamKind::Any]),
],
ReturnType::Integer,
STANDARD,
"Returns the 1-based position of FindText inside WithinText, starting at StartPosition \
(default 1). Unlike FIND the comparison ignores case but remains accent-sensitive, and \
the search text treats `?` and `*` as wildcards with `~` as the escape character. If the \
text is absent the function returns NotFoundValue when supplied, otherwise it raises an \
error.",
&["SEARCH ( \"red\", \"GridCraft Cell S100 Red\" )", "SEARCH ( \"cell*s100\", \"GridCraft Cell S100 Blue\", 1, BLANK () )"],
),
spec(
"SUBSTITUTE",
FunctionCategory::Text,
3,
4,
&[
required("Text", ParamKind::Text),
required("OldText", ParamKind::Text),
required("NewText", ParamKind::Text),
optional("InstanceNumber", ParamKind::Number),
],
&[
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text]),
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text, ParamKind::Number]),
],
ReturnType::String,
STANDARD,
"Replaces occurrences of OldText with NewText in a text value. With no InstanceNumber \
every occurrence is replaced; otherwise only that occurrence is. Matching is \
case-sensitive and accent-sensitive, so a difference in case leaves the text untouched, \
and the search text is a literal substring rather than a pattern.",
&["SUBSTITUTE ( \"GridCraft Cell S100 Red\", \"Cell\", \"Tablet\" )", "SUBSTITUTE ( \"GridCraft Cell S100 Red\", \"S\", \"X\", 1 )"],
),
spec(
"TOCSV",
FunctionCategory::Text,
1,
4,
&[
required("Table", ParamKind::Table),
optional("MaxRows", ParamKind::Number),
optional("Delimiter", ParamKind::Text),
optional("IncludeHeaders", ParamKind::Boolean),
],
&[
overload(&[ParamKind::Table]),
overload(&[ParamKind::Table, ParamKind::Number]),
overload(&[ParamKind::Table, ParamKind::Number, ParamKind::Text]),
overload(&[ParamKind::Table, ParamKind::Number, ParamKind::Text, ParamKind::Boolean]),
],
ReturnType::String,
ENGINE_ONLY,
"Serializes a table's records as comma-separated text. MaxRows limits how many rows are \
converted (default 10, negative for all), Delimiter is a non-empty constant field \
separator (default a comma), and IncludeHeaders controls the header row (default TRUE). \
Row order is unspecified and line endings are fixed; quotation marks are doubled, and a \
value containing a quote or the delimiter is enclosed in quotes. Not available in Excel, \
and not supported in DirectQuery calculated columns.",
&["TOCSV ( Customer )", "TOCSV ( Customer, 3, \",\", FALSE )"],
),
spec(
"TOJSON",
FunctionCategory::Text,
1,
2,
&[required("Table", ParamKind::Table), optional("MaxRows", ParamKind::Number)],
&[overload(&[ParamKind::Table]), overload(&[ParamKind::Table, ParamKind::Number])],
ReturnType::String,
ENGINE_ONLY,
"Serializes a table's records as a JSON document with header, rowCount and data members. \
MaxRows limits how many rows are converted (default 10, negative for all), while values \
keep their native types inside the JSON text. Row order is unspecified. Not available in \
Excel, and not supported in DirectQuery calculated columns.",
&["TOJSON ( Customer )", "TOJSON ( Customer, 3 )"],
),
spec(
"TRIM",
FunctionCategory::Text,
1,
1,
&[required("Text", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::String,
STANDARD,
"Removes leading and trailing spaces and collapses runs of spaces between words to a \
single space. Only the 7-bit ASCII space (character 32) is removed: the non-breaking \
space (character 160), tabs and other whitespace survive, which matters for text copied \
from web pages.",
&["TRIM ( \" DAX is awesome !!! \" )", "TRIM ( Customer[Customer Name] )"],
),
spec(
"UNICHAR",
FunctionCategory::Text,
1,
1,
&[required("Number", ParamKind::Number)],
&[overload(&[ParamKind::Number])],
ReturnType::String,
STANDARD,
"Returns the Unicode character for a numeric code point. A supplementary character is \
one code point value. Code point 0 and values outside the allowable Unicode range \
raise an error.",
&["UNICHAR ( 9473 )", "UNICHAR ( 65 )"],
),
spec(
"UNICODE",
FunctionCategory::Text,
1,
1,
&[required("Text", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::Integer,
STANDARD,
"Returns the numeric Unicode value of the first character of a text value; an empty \
string raises an error. The engine counts Unicode code points, so a character outside \
the Basic Multilingual Plane is returned as one value. Use UNICHAR for the inverse \
conversion.",
&["UNICODE ( \"A\" )", "UNICODE ( Customer[CountryRegion] )"],
),
spec(
"UPPER",
FunctionCategory::Text,
1,
1,
&[required("Text", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::String,
STANDARD,
"Converts every letter in a text value to uppercase and returns the result. Case mapping \
follows Unicode rules and is locale-sensitive for some scripts, such as the Turkish \
dotted and dotless I, while digits and symbols are left unchanged.",
&["UPPER ( \"dax is so cool!\" )", "UPPER ( Customer[CountryRegion] )"],
),
spec(
"VALUE",
FunctionCategory::Text,
1,
1,
&[required("Text", ParamKind::Text)],
&[overload(&[ParamKind::Text])],
ReturnType::Decimal,
STANDARD,
"Converts text that represents a number, date or time into its numeric value. Parsing \
accepts the constant, number and date/time formats the engine recognizes and follows the \
model locale for separators and date order; text that cannot be parsed raises an error. \
Because the engine also coerces text implicitly, VALUE mainly makes the conversion \
explicit, and it should be protected with IF when the column may contain invalid text.",
&["VALUE ( \"123.45678\" )", "VALUE ( \"2020-10-23\" )", "VALUE ( Sales[TextAmount] )"],
),
];
@@ -0,0 +1,716 @@
//! Time intelligence functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! Every function in this category assumes a well-formed date table: a contiguous range of
//! dates, one unique date/date-time column marked as the date table, and a relationship to the
//! fact table based on that column (or the table explicitly marked as a date table). The
//! optional `YearEndDate` arguments control fiscal years; the week-based functions and the
//! calendar-only arguments introduced with model calendars require a calendar reference rather
//! than a date column and are not available to Excel's embedded engine.
use super::{FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec};
use crate::functions::FunctionCategory;
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"CLOSINGBALANCEMONTH",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression at the last date of the current month, after applying the \
optional filter. It opens a month-to-date window only at its closing date, so a filter \
on the date table is replaced by ENDOFMONTH; the date table must be contiguous and \
marked as a date table for the relationship to be treated as a calendar.",
&["CLOSINGBALANCEMONTH ( [Sales Amount], 'Date'[Date] )"],
),
spec(
"CLOSINGBALANCEQUARTER",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression at the last date of the current quarter, after applying the \
optional filter. The quarter is derived from the marked date table, so missing dates or \
a relationship not based on the date column invalidate the closing balance.",
&["CLOSINGBALANCEQUARTER ( [Sales Amount], 'Date'[Date] )"],
),
spec(
"CLOSINGBALANCEWEEK",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, false, true),
"Evaluates the expression at the last date of the current week of a model calendar, \
after applying the optional filter. Week boundaries come from the calendar definition, \
so a plain date column is not accepted and the calendar must define week categories.",
&["CLOSINGBALANCEWEEK ( [Sales Amount], Gregorian )"],
),
spec(
"CLOSINGBALANCEYEAR",
FunctionCategory::TimeIntelligence,
2,
4,
&[
required("Expression", ParamKind::Expression),
required("Dates", ParamKind::Date),
optional("Filter", ParamKind::Any),
optional("YearEndDate", ParamKind::Text),
],
&[
overload(&[ParamKind::Expression, ParamKind::Date]),
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression at the last date of the current year, after applying the \
optional filter. Pass YearEndDate to make the closing date follow a fiscal year; the \
date table must contain every day of that fiscal year and stay marked as a date table.",
&["CLOSINGBALANCEYEAR ( [Sales Amount], 'Date'[Date] )", "CLOSINGBALANCEYEAR ( [Sales Amount], 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )"],
),
spec(
"DATEADD",
FunctionCategory::TimeIntelligence,
3,
5,
&[
required("Dates", ParamKind::Date),
required("NumberOfIntervals", ParamKind::Number),
required("Interval", ParamKind::Text),
optional("Extension", ParamKind::Text),
optional("Truncation", ParamKind::Text),
],
&[
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text]),
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text]),
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text, ParamKind::Text]),
],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Shifts the dates visible in the filter context by NumberOfIntervals units of Interval \
(DAY, MONTH, QUARTER or YEAR) and returns the dates that exist in the date column. \
Extension and Truncation are available only for a model calendar; for a date column \
DATEADD accepts exactly three arguments. With a calendar, YEAR follows the calendar's \
year definition, which may be a fiscal year.",
&["DATEADD ( 'Date'[Date], -1, YEAR )", "DATEADD ( Gregorian, 1, MONTH )", "DATEADD ( Gregorian, 1, MONTH, EXTENDING, ANCHORED )"],
),
spec(
"DATESBETWEEN",
FunctionCategory::TimeIntelligence,
3,
3,
&[required("Dates", ParamKind::Date), required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date)],
&[overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the dates between two inclusive boundaries that exist in the date column. A \
BLANK StartDate begins at MIN ( Dates ), a BLANK EndDate ends at MAX ( Dates ), and a \
StartDate after EndDate returns an empty table. The result keeps the lineage of the \
marked date table, so the date table must be contiguous for windows to be meaningful.",
&["DATESBETWEEN ( 'Date'[Date], DATE ( 2008, 8, 1 ), DATE ( 2008, 8, 31 ) )"],
),
spec(
"DATESINPERIOD",
FunctionCategory::TimeIntelligence,
4,
5,
&[
required("Dates", ParamKind::Date),
required("StartDate", ParamKind::Date),
required("NumberOfIntervals", ParamKind::Number),
required("Interval", ParamKind::Text),
optional("EndBehavior", ParamKind::Text),
],
&[
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Text]),
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text]),
],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the dates from StartDate over NumberOfIntervals units of Interval (DAY, WEEK, \
MONTH, QUARTER or YEAR); a negative count looks backwards. BLANK StartDate uses the \
minimum date in the column. EndBehavior (PRECISE or ENDALIGNED) is available only with \
a model calendar; consider WINDOW when the interval arithmetic is not needed.",
&[
"DATESINPERIOD ( 'Date'[Date], MAX ( 'Date'[Date] ), -12, MONTH )",
"DATESINPERIOD ( Gregorian, DATE ( 2008, 2, 29 ), -1, MONTH, ENDALIGNED )",
],
),
spec(
"DATESMTD",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Month-to-date window: from the first day of the month up to whatever latest date the \
filter context exposes, restricted to dates present in the column. This is syntax sugar \
for DATESBETWEEN over the current month and requires a marked, contiguous date table.",
&["DATESMTD ( 'Date'[Date] )"],
),
spec(
"DATESQTD",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Quarter-to-date window: from the first day of the current quarter up to whatever latest \
date the filter context exposes. Quarter boundaries come from the marked date table, so \
an incomplete or unmarked date table breaks the window.",
&["DATESQTD ( 'Date'[Date] )"],
),
spec(
"DATESWTD",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Calendar", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, true),
"Returns the week-to-date window of a model calendar: dates from the first day of the \
current week through the last visible date. Week numbering and the first day of the week \
come from the calendar definition, not from the date column, and the function is not \
available to Excel's DAX engine.",
&["DATESWTD ( Gregorian )"],
),
spec(
"DATESYTD",
FunctionCategory::TimeIntelligence,
1,
2,
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Year-to-date window: from the start of the year up to whatever latest date the filter \
context exposes, keeping only dates present in the column. YearEndDate selects a fiscal \
year end (for example \"6/30\"); the date table must cover whole fiscal years and be \
marked as a date table for the window to be correct.",
&["DATESYTD ( 'Date'[Date] )", "DATESYTD ( 'Date'[Date], \"6/30/2008\" )"],
),
spec(
"ENDOFMONTH",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the last date of the month visible in the filter context as a single-row table: \
the latest date of that month that exists in the date column of the marked date table. Use it as a CALCULATE \
modifier for semi-additive measures.",
&["ENDOFMONTH ( 'Date'[Date] )"],
),
spec(
"ENDOFQUARTER",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the last date of the quarter visible in the filter context as a single-row table, \
restricted to dates present in the date column. Quarter boundaries follow the marked \
date table; a non-contiguous table can omit the quarter-end date.",
&["ENDOFQUARTER ( 'Date'[Date] )"],
),
spec(
"ENDOFWEEK",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Calendar", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, true),
"Returns the last date of the week visible in the filter context for a model calendar. \
The week definition, including the first day of the week, comes from the calendar, so a \
date column is not accepted and Excel's DAX engine does not support the function.",
&["ENDOFWEEK ( Gregorian )"],
),
spec(
"ENDOFYEAR",
FunctionCategory::TimeIntelligence,
1,
2,
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the last date of the year visible in the filter context as a single-row table. \
YearEndDate selects a fiscal year end; without it the window is December 31. The date \
table must be marked and must contain the resulting date.",
&["ENDOFYEAR ( 'Date'[Date] )", "ENDOFYEAR ( 'Date'[Date], \"6/30/2008\" )"],
),
spec(
"FIRSTDATE",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the first date visible in the filter context, as a single-row table, restricted \
to dates that exist in the date column. Blanks are considered, unlike FIRSTNONBLANK; \
the column's table needs the date table marking so that time intelligence windows \
behave correctly.",
&["FIRSTDATE ( 'Date'[Date] )"],
),
spec(
"FIRSTNONBLANK",
FunctionCategory::TimeIntelligence,
2,
2,
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Column, ParamKind::Expression])],
ReturnType::Table,
FunctionFlags::new(true, false, false, true, true),
"Iterates the column in its sort order and returns the first value for which the \
expression is not blank, as a single-column, single-row table. The column need not be a \
date, but over a marked date table it defines the start of the time window; the iterator \
can cause performance and memory issues on large models, so prefer an optimized pattern.",
&["FIRSTNONBLANK ( 'Date'[Date], [Sales Amount] )"],
),
spec(
"FIRSTNONBLANKVALUE",
FunctionCategory::TimeIntelligence,
2,
2,
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Column, ParamKind::Expression])],
ReturnType::Any,
FunctionFlags::new(true, false, false, true, true),
"Returns the expression evaluated at the start of the visible time window: the first \
value of the column whose expression is not blank, without returning a table. It is the \
scalar counterpart of FIRSTNONBLANK and is commonly used for semi-additive measures over \
a marked date table; the evaluation is an iterator, so large models pay per-row cost.",
&["FIRSTNONBLANKVALUE ( 'Date'[Date], [Sales Amount] )"],
),
spec(
"LASTDATE",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the last date visible in the filter context, as a single-row table, restricted \
to dates that exist in the date column. It is the anchor of many YTD windows; a missing \
or unmarked date table makes the result follow partial selections instead of the calendar.",
&["LASTDATE ( 'Date'[Date] )"],
),
spec(
"LASTNONBLANK",
FunctionCategory::TimeIntelligence,
2,
2,
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Column, ParamKind::Expression])],
ReturnType::Table,
FunctionFlags::new(true, false, false, true, true),
"Iterates the column in its sort order and returns the last value for which the \
expression is not blank, as a single-column, single-row table. The column need not be a \
date, but over a marked date table it defines the end of the time window; the iterator \
can be expensive, so dax.guide recommends optimized semi-additive patterns.",
&["LASTNONBLANK ( 'Date'[Date], [Sales Amount] )"],
),
spec(
"LASTNONBLANKVALUE",
FunctionCategory::TimeIntelligence,
2,
2,
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
&[overload(&[ParamKind::Column, ParamKind::Expression])],
ReturnType::Any,
FunctionFlags::new(true, false, false, true, true),
"Returns the expression evaluated at the end of the visible time window: the last value \
of the column whose expression is not blank, without returning a table. It is the scalar \
counterpart of LASTNONBLANK and a typical semi-additive pattern over a marked date \
table; the per-row iteration is costly on large models.",
&["LASTNONBLANKVALUE ( 'Date'[Date], [Sales Amount] )"],
),
spec(
"NEXTDAY",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the day after the last date visible in the filter context, as a single-row table \
restricted to dates present in the date column. Because the date table must be \
contiguous, a missing next day yields an empty table.",
&["NEXTDAY ( 'Date'[Date] )"],
),
spec(
"NEXTMONTH",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns all dates of the month after the last date visible in the filter context. The \
month boundaries come from the marked date table, so gaps in the calendar produce \
incomplete results and a bad relationship makes the window follow the wrong selection.",
&["NEXTMONTH ( 'Date'[Date] )"],
),
spec(
"NEXTQUARTER",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns all dates of the quarter after the last date visible in the filter context. The \
quarter is derived from the marked date table; the result keeps the date column lineage \
and excludes dates absent from the calendar.",
&["NEXTQUARTER ( 'Date'[Date] )"],
),
spec(
"NEXTWEEK",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Calendar", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, true),
"Returns all dates of the week after the last date visible in the filter context, using \
the week definition of a model calendar. A plain date column cannot supply week \
boundaries, and Excel's embedded DAX engine does not expose the calendar-based function.",
&["NEXTWEEK ( Gregorian )"],
),
spec(
"NEXTYEAR",
FunctionCategory::TimeIntelligence,
1,
2,
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns all dates of the year after the last date visible in the filter context. \
YearEndDate shifts the year to a fiscal calendar; the date table must contain the whole \
following year, be contiguous and be marked as a date table.",
&["NEXTYEAR ( 'Date'[Date] )", "NEXTYEAR ( 'Date'[Date], \"6/30/2008\" )"],
),
spec(
"OPENINGBALANCEMONTH",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression on the final date of the preceding month, after applying the \
optional filter. The opening balance uses the marked date table's month boundaries, so \
the relationship and date coverage must be valid or the window slides on partial data.",
&["OPENINGBALANCEMONTH ( [Sales Amount], 'Date'[Date] )"],
),
spec(
"OPENINGBALANCEQUARTER",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression on the final date of the preceding quarter, after applying the \
optional filter. Quarter boundaries come from the marked date table; an unmarked table \
or a relationship not based on the date column changes the opening period.",
&["OPENINGBALANCEQUARTER ( [Sales Amount], 'Date'[Date] )"],
),
spec(
"OPENINGBALANCEWEEK",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, false, true),
"Evaluates the expression on the final date of the preceding week of a model calendar, \
after applying the optional filter. The calendar defines the week, so a date column is \
not accepted and the function is unavailable to Excel's DAX engine.",
&["OPENINGBALANCEWEEK ( [Sales Amount], Gregorian )"],
),
spec(
"OPENINGBALANCEYEAR",
FunctionCategory::TimeIntelligence,
2,
4,
&[
required("Expression", ParamKind::Expression),
required("Dates", ParamKind::Date),
optional("Filter", ParamKind::Any),
optional("YearEndDate", ParamKind::Text),
],
&[
overload(&[ParamKind::Expression, ParamKind::Date]),
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression on the final date of the preceding year, after applying the \
optional filter. YearEndDate aligns the opening balance with a fiscal year; the date \
table must cover entire fiscal years and be marked as a date table.",
&["OPENINGBALANCEYEAR ( [Sales Amount], 'Date'[Date] )", "OPENINGBALANCEYEAR ( [Sales Amount], 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )"],
),
spec(
"PARALLELPERIOD",
FunctionCategory::TimeIntelligence,
3,
3,
&[required("Dates", ParamKind::Date), required("NumberOfIntervals", ParamKind::Number), required("Interval", ParamKind::Text)],
&[overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Moves the visible first and last dates by NumberOfIntervals units of MONTH, QUARTER or \
YEAR, then returns the contiguous dates between the moved boundaries, expanding partial \
periods to complete ones. Only dates in the marked date column appear, so a \
discontinuous calendar leaves gaps.",
&["PARALLELPERIOD ( 'Date'[Date], -1, YEAR )", "PARALLELPERIOD ( 'Date'[Date], 0, MONTH )"],
),
spec(
"PREVIOUSDAY",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the day before the first date visible in the filter context, as a single-row \
table restricted to dates present in the date column. The marked date table must be \
contiguous; otherwise the previous day may not exist in the model.",
&["PREVIOUSDAY ( 'Date'[Date] )"],
),
spec(
"PREVIOUSMONTH",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns all dates of the month before the first date visible in the filter context. Month \
boundaries come from the marked date table; gaps in the calendar or an incorrect \
relationship make the previous month incomplete.",
&["PREVIOUSMONTH ( 'Date'[Date] )"],
),
spec(
"PREVIOUSQUARTER",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns all dates of the quarter before the first date visible in the filter context. The \
quarter is derived from the marked date table, so the table must contain every day of \
the previous quarter for the window to be complete.",
&["PREVIOUSQUARTER ( 'Date'[Date] )"],
),
spec(
"PREVIOUSWEEK",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Calendar", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, true),
"Returns all dates of the week before the first date visible in the filter context, using \
a model calendar's week definition. Week boundaries are calendar metadata, so a date \
column is not accepted and Excel's DAX engine cannot call the function.",
&["PREVIOUSWEEK ( Gregorian )"],
),
spec(
"PREVIOUSYEAR",
FunctionCategory::TimeIntelligence,
1,
2,
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns all dates of the year before the first date visible in the filter context, \
optionally aligned to a fiscal year end. The marked date table must include the whole \
previous year, including leap days, for the window to be complete.",
&["PREVIOUSYEAR ( 'Date'[Date] )", "PREVIOUSYEAR ( 'Date'[Date], \"6/30/2008\" )"],
),
spec(
"SAMEPERIODLASTYEAR",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the dates of the same period one year earlier, preserving the number of days \
rather than the month boundaries. It is syntax sugar for DATEADD ( Dates, -1, YEAR ) and \
relies on a marked, contiguous date table; a fiscal year requires adapting the offset \
or the calendar definition.",
&["SAMEPERIODLASTYEAR ( 'Date'[Date] )"],
),
spec(
"STARTOFMONTH",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the first date of the month visible in the filter context, as a single-row table \
restricted to dates in the date column. The marked date table must contain the month's \
first day for the result to be non-empty.",
&["STARTOFMONTH ( 'Date'[Date] )"],
),
spec(
"STARTOFQUARTER",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Dates", ParamKind::Date)],
&[overload(&[ParamKind::Date])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the first date of the quarter visible in the filter context, as a single-row \
table restricted to dates in the date column. Quarter boundaries follow the marked date \
table, so an incomplete calendar can omit the first day.",
&["STARTOFQUARTER ( 'Date'[Date] )"],
),
spec(
"STARTOFWEEK",
FunctionCategory::TimeIntelligence,
1,
1,
&[required("Calendar", ParamKind::Table)],
&[overload(&[ParamKind::Table])],
ReturnType::Table,
FunctionFlags::new(false, false, false, false, true),
"Returns the first date of the week visible in the filter context for a model calendar. \
The calendar defines the first day of the week, so a date column is not accepted and the \
function is not available to Excel's embedded DAX engine.",
&["STARTOFWEEK ( Gregorian )"],
),
spec(
"STARTOFYEAR",
FunctionCategory::TimeIntelligence,
1,
2,
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
ReturnType::Table,
FunctionFlags::new(false, false, false, true, true),
"Returns the first date of the year visible in the filter context as a single-row table. \
YearEndDate shifts the start to a fiscal year; the date table must be marked and include \
every day from the fiscal-year start through year end.",
&["STARTOFYEAR ( 'Date'[Date] )", "STARTOFYEAR ( 'Date'[Date], \"6/30/2008\" )"],
),
spec(
"TOTALMTD",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression over the month-to-date window, from the first day of the month \
through the last visible date, after applying the optional filter. It is syntax sugar \
for CALCULATE with DATESMTD and depends on a marked, contiguous date table.",
&["TOTALMTD ( SUM ( Sales[Amount] ), 'Date'[Date] )"],
),
spec(
"TOTALQTD",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression over the quarter-to-date window, from the first day of the \
quarter through the last visible date, after applying the optional filter. It is syntax \
sugar for CALCULATE with DATESQTD and requires the date table to be marked.",
&["TOTALQTD ( SUM ( Sales[Amount] ), 'Date'[Date] )"],
),
spec(
"TOTALWTD",
FunctionCategory::TimeIntelligence,
2,
3,
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
ReturnType::Any,
FunctionFlags::new(false, false, false, false, true),
"Evaluates the expression over the week-to-date window defined by a model calendar, from \
the first day of the week through the last visible date, after applying the optional \
filter. Week boundaries come from the calendar, and Excel's DAX engine does not support \
the function.",
&["TOTALWTD ( SUM ( Sales[Amount] ), Gregorian )"],
),
spec(
"TOTALYTD",
FunctionCategory::TimeIntelligence,
2,
4,
&[
required("Expression", ParamKind::Expression),
required("Dates", ParamKind::Date),
optional("Filter", ParamKind::Any),
optional("YearEndDate", ParamKind::Text),
],
&[
overload(&[ParamKind::Expression, ParamKind::Date]),
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
],
ReturnType::Any,
FunctionFlags::new(false, false, false, true, true),
"Evaluates the expression over the year-to-date window, from the first day of the year \
through the last visible date, after applying the optional filter. It is syntax sugar \
for CALCULATE with DATESYTD; YearEndDate selects a fiscal year and the date table must \
be marked and cover whole fiscal years.",
&[
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date] )",
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date], Sales[Region] = \"US\" )",
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )",
],
),
];
@@ -0,0 +1,295 @@
//! Visual calculation functions.
//!
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
//! kinds, overloads, return type, flags, description and parseable examples.
//!
//! All functions in this category are Power BI visual calculation functions: they can only be
//! used in the visual calculation editor and are rejected in measures, calculated columns and
//! calculated tables. The `axis` parameter is defined by the VISUAL SHAPE query syntax emitted
//! by the visual calculation feature, so `ROWS` and `COLUMNS` appear in examples as bare names.
use super::{FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
/// Power BI visual calculations are not available to Excel's embedded engine, and the
/// DirectQuery restrictions listed for measures and calculated columns do not apply because
/// the functions cannot be used there.
const VISUAL: FunctionFlags = FunctionFlags::new(false, false, false, false, false);
pub static FUNCTIONS: &[FunctionSpec] = &[
spec(
"COLLAPSE",
super::FunctionCategory::VisualCalculations,
1,
usize::MAX,
&[
required("Expression", ParamKind::Any),
optional("Axis", ParamKind::Any),
optional("Column", ParamKind::Column),
optional("N", ParamKind::Number),
],
&[overload(&[ParamKind::Any]), variadic(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
VISUAL,
"Retrieves a context with the detail levels above the current one removed, or returns its \
first argument evaluated in that coarser context. Navigation-only calls (an axis or a \
list of columns) can be used inside CALCULATE. Available only in Power BI visual \
calculations; `N` defaults to one level.",
&[
"COLLAPSE ( [Sales Amount], ROWS )",
"COLLAPSE ( [Sales Amount], ROWS, 2 )",
"COLLAPSE ( [Sales Amount], [Month] )",
"COLLAPSE ( ROWS, 1 )",
],
),
spec(
"COLLAPSEALL",
super::FunctionCategory::VisualCalculations,
1,
2,
&[optional("Expression", ParamKind::Any), required("Axis", ParamKind::Any)],
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
VISUAL,
"Removes every detail level along an axis, returning the expression evaluated at the \
highest level of that axis. The inverse of EXPANDALL. Available only in Power BI visual \
calculations.",
&["COLLAPSEALL ( [Sales Amount], ROWS )", "COLLAPSEALL ( ROWS )", "COLLAPSEALL ( [Sales Amount], COLUMNS )"],
),
spec(
"EXPAND",
super::FunctionCategory::VisualCalculations,
1,
usize::MAX,
&[
required("Expression", ParamKind::Any),
optional("Axis", ParamKind::Any),
optional("Column", ParamKind::Column),
optional("N", ParamKind::Number),
],
&[overload(&[ParamKind::Any]), variadic(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
VISUAL,
"Retrieves a context with additional detail levels compared to the current one, or \
returns its first argument evaluated in that finer context. Navigation-only calls (an \
axis or a list of columns) can be used inside CALCULATE. Available only in Power BI \
visual calculations; `N` defaults to one level.",
&["EXPAND ( [Sales Amount], ROWS )", "EXPAND ( [Sales Amount], ROWS, 2 )", "EXPAND ( [Sales Amount], [Month] )"],
),
spec(
"EXPANDALL",
super::FunctionCategory::VisualCalculations,
1,
2,
&[optional("Expression", ParamKind::Any), required("Axis", ParamKind::Any)],
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Any])],
ReturnType::Any,
VISUAL,
"Adds every detail level along an axis, returning the expression evaluated at the lowest \
level of that axis. The inverse of COLLAPSEALL. Available only in Power BI visual \
calculations.",
&["EXPANDALL ( [Sales Amount], ROWS )", "EXPANDALL ( ROWS )", "EXPANDALL ( [Sales Amount], COLUMNS )"],
),
spec(
"FIRST",
super::FunctionCategory::VisualCalculations,
1,
5,
&[
required("Column", ParamKind::Column),
optional("Axis", ParamKind::Any),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Column]),
overload(&[ParamKind::Column, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Any,
VISUAL,
"Returns the value of a column in the first row of an axis or partition. OrderBy columns \
define the sort order; Blanks accepts DEFAULT, FIRST or LAST and Reset accepts NONE, \
LOWESTPARENT, HIGHESTPARENT or a level number. Available only in Power BI visual \
calculations.",
&["FIRST ( [Sales Amount] )", "FIRST ( [Sales Amount], ROWS )", "FIRST ( [Sales Amount], ROWS, [Month], DEFAULT, NONE )"],
),
spec(
"LAST",
super::FunctionCategory::VisualCalculations,
1,
5,
&[
required("Column", ParamKind::Column),
optional("Axis", ParamKind::Any),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Column]),
overload(&[ParamKind::Column, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Any,
VISUAL,
"Returns the value of a column in the last row of an axis or partition. OrderBy columns \
define the sort order; Blanks accepts DEFAULT, FIRST or LAST and Reset accepts NONE, \
LOWESTPARENT, HIGHESTPARENT or a level number. Available only in Power BI visual \
calculations.",
&["LAST ( [Sales Amount] )", "LAST ( [Sales Amount], ROWS )", "LAST ( [Sales Amount], ROWS, [Month], FIRST, LOWESTPARENT )"],
),
spec(
"MOVINGAVERAGE",
super::FunctionCategory::VisualCalculations,
2,
7,
&[
required("Column", ParamKind::Column),
required("WindowSize", ParamKind::Number),
optional("IncludeCurrent", ParamKind::Boolean),
optional("Axis", ParamKind::Any),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Column, ParamKind::Number]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Numeric,
VISUAL,
"Calculates the average of the values in a sliding window of WindowSize rows along an \
axis. IncludeCurrent defaults to TRUE; when FALSE the window holds the previous \
WindowSize rows. OrderBy, Blanks and Reset behave as in FIRST. Available only in Power \
BI visual calculations.",
&[
"MOVINGAVERAGE ( [Sales Amount], 6 )",
"MOVINGAVERAGE ( [Sales Amount], 3, FALSE )",
"MOVINGAVERAGE ( [Sales Amount], 6, TRUE, ROWS )",
"MOVINGAVERAGE ( [Sales Amount], 12, TRUE, ROWS, [Month], DEFAULT, NONE )",
],
),
spec(
"NEXT",
super::FunctionCategory::VisualCalculations,
1,
6,
&[
required("Column", ParamKind::Column),
optional("Steps", ParamKind::Number),
optional("Axis", ParamKind::Any),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Column]),
overload(&[ParamKind::Column, ParamKind::Number]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Any,
VISUAL,
"Returns the value of a column the given number of rows after the current row on an axis. \
Steps defaults to 1 and must be at least 1. OrderBy, Blanks and Reset behave as in \
FIRST. Available only in Power BI visual calculations.",
&["NEXT ( [Sales Amount] )", "NEXT ( [Sales Amount], 1, ROWS )", "NEXT ( [Sales Amount], 2, ROWS, [Month], LAST, HIGHESTPARENT )"],
),
spec(
"PREVIOUS",
super::FunctionCategory::VisualCalculations,
1,
6,
&[
required("Column", ParamKind::Column),
optional("Steps", ParamKind::Number),
optional("Axis", ParamKind::Any),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Column]),
overload(&[ParamKind::Column, ParamKind::Number]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Any,
VISUAL,
"Returns the value of a column the given number of rows before the current row on an \
axis. Steps defaults to 1 and is negated internally, so it must be at least 1. OrderBy, \
Blanks and Reset behave as in FIRST. Available only in Power BI visual calculations.",
&[
"PREVIOUS ( [Sales Amount] )",
"PREVIOUS ( [Sales Amount], 1, ROWS )",
"PREVIOUS ( [Sales Amount], 2, ROWS, [Month], DEFAULT, LOWESTPARENT )",
],
),
spec(
"RANGE",
super::FunctionCategory::VisualCalculations,
1,
6,
&[
required("Step", ParamKind::Number),
optional("IncludeCurrent", ParamKind::Boolean),
optional("Axis", ParamKind::Any),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Number]),
overload(&[ParamKind::Number, ParamKind::Boolean]),
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Table,
VISUAL,
"Returns the interval of rows within an axis that starts Step rows before (negative Step) \
or after (non-negative Step) the current row, optionally including the current row. The \
result is normally passed to CALCULATE. Available only in Power BI visual calculations.",
&["RANGE ( 6 )", "RANGE ( -5, TRUE, ROWS )", "RANGE ( 12, FALSE, ROWS, [Month], DEFAULT, NONE )"],
),
spec(
"RUNNINGSUM",
super::FunctionCategory::VisualCalculations,
1,
5,
&[
required("Column", ParamKind::Column),
optional("Axis", ParamKind::Any),
optional("OrderBy", ParamKind::Any),
optional("Blanks", ParamKind::Any),
optional("Reset", ParamKind::Any),
],
&[
overload(&[ParamKind::Column]),
overload(&[ParamKind::Column, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
],
ReturnType::Numeric,
VISUAL,
"Calculates the cumulative sum of a column from the start of the axis or partition up to \
the current row. OrderBy, Blanks and Reset behave as in FIRST. Available only in Power \
BI visual calculations.",
&["RUNNINGSUM ( [Sales Amount] )", "RUNNINGSUM ( [Sales Amount], ROWS )", "RUNNINGSUM ( [Sales Amount], ROWS, [Month], DEFAULT, NONE )"],
),
];
File diff suppressed because it is too large Load Diff
+553
View File
@@ -0,0 +1,553 @@
//! Tokenizer for DAX expressions.
//!
//! Spans are byte offsets into the source. Keywords are recognised case-insensitively; the
//! parser keeps the source spelling of identifiers and function names. `TRUE`/`FALSE` stay
//! identifiers here so the parser can tell the boolean literal from a call such as `TRUE()`.
//!
//! Numeric tokens are typed: digit-only text becomes [`TokenKind::Integer`] when it fits `i64`,
//! while a decimal point or exponent becomes [`TokenKind::Decimal`]. `dt"..."` text is
//! validated here and emitted as [`TokenKind::DateTime`]. Overflow and malformed date/time
//! literals are [`LexError`] values carrying the literal's span.
//!
//! Statement punctuation is lexed here too: `:` ([`TokenKind::Colon`]) separates a function
//! parameter's name from its annotation, `@name` becomes [`TokenKind::AtName`] for `START AT`
//! parameters, and `;` ([`TokenKind::Semicolon`]) is the optional trailing query terminator.
//! Statement keywords such as `DEFINE` and `MEASURE` stay plain [`TokenKind::Ident`] tokens and
//! are matched case-insensitively by the parser, so they remain available as identifier text
//! wherever the grammar does not reserve them.
use chrono::NaiveDate;
use crate::ast::{DateTimeLiteral, Span};
/// Longest expression accepted by [`crate::parse_expression`], in bytes. Mirrors DAX's
/// expression limit and bounds the size of the tree a long operator chain can build.
pub const MAX_INPUT_LEN: usize = 8_192;
/// Longest query accepted by [`crate::parse_query`], in bytes. A query has no documented length
/// limit comparable to the expression bound, so it gets a larger, independent ceiling that still
/// bounds memory for `DEFINE` blocks and repeated `EVALUATE` statements.
pub const MAX_QUERY_LEN: usize = 1_048_576;
/// A lexical token.
#[derive(Clone, Debug, PartialEq)]
pub enum TokenKind {
/// A digit-only literal that fits in `i64`, e.g. `42`.
Integer(i64),
/// A literal with a decimal point or exponent, e.g. `3.14`, `.5`, `1e3`.
Decimal(f64),
/// A validated `dt"..."` date/time literal.
DateTime(DateTimeLiteral),
String(String),
/// A bare identifier, function name or table name (`Sales`, `STDEV.P`, `TRUE`).
Ident(String),
/// A single-quoted table name, with `''` escapes resolved.
QuotedIdent(String),
/// A bracketed column name, with `]]` escapes resolved.
BracketIdent(String),
/// The `NOT` operator (case-insensitive).
Not,
/// The `IN` operator (case-insensitive).
In,
/// The `EVALUATE` statement keyword (case-insensitive).
Evaluate,
Plus,
Minus,
Star,
Slash,
Caret,
Amp,
Eq,
StrictEq,
NotEq,
Lt,
Gt,
Le,
Ge,
AndAnd,
OrOr,
/// `=>`, used by `DEFINE FUNCTION` definitions.
Arrow,
/// `:` between a function parameter name and its type annotation.
Colon,
/// `@name`, an XMLA statement parameter reference in `START AT`.
AtName(String),
/// `;`, accepted only as an optional trailing statement terminator.
Semicolon,
LParen,
RParen,
LBrace,
RBrace,
Comma,
Eof,
}
/// A token and its byte span.
#[derive(Clone, Debug, PartialEq)]
pub struct Token {
pub kind: TokenKind,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("{message} at bytes {}..{}", span.start, span.end)]
pub struct LexError {
pub message: String,
pub span: Span,
}
impl LexError {
fn new(message: impl Into<String>, span: Span) -> Self {
LexError { message: message.into(), span }
}
}
/// Tokenizes `src` and appends an [`TokenKind::Eof`] token at `src.len()`.
///
/// Whitespace is insignificant and comments (`//`, `--` to end of line, and `/* ... */`) are
/// skipped. A block comment does not nest.
#[allow(clippy::cognitive_complexity)]
// A hand-written scanner: one loop with a case per token kind.
pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
let chars: Vec<(usize, char)> = src.char_indices().collect();
let n = chars.len();
let ch = |i: usize| chars.get(i).map(|(_, c)| *c);
let pos = |i: usize| chars.get(i).map(|(p, _)| *p).unwrap_or(src.len());
let mut out: Vec<Token> = Vec::new();
let mut i = 0usize;
while i < n {
let start = pos(i);
let Some(c) = ch(i) else { break };
match c {
c if c.is_whitespace() => {
i += 1;
}
'/' if ch(i + 1) == Some('/') => {
i += 2;
while ch(i).is_some_and(|c| c != '\n' && c != '\r') {
i += 1;
}
}
'-' if ch(i + 1) == Some('-') => {
i += 2;
while ch(i).is_some_and(|c| c != '\n' && c != '\r') {
i += 1;
}
}
'/' if ch(i + 1) == Some('*') => {
let mut j = i + 2;
loop {
match ch(j) {
None => {
return Err(LexError::new("unterminated block comment", Span::new(start, src.len())));
}
Some('*') if ch(j + 1) == Some('/') => {
j += 2;
break;
}
Some(_) => j += 1,
}
}
i = j;
}
'"' => {
let mut text = String::new();
let mut j = i + 1;
loop {
match ch(j) {
None => return Err(LexError::new("unterminated string literal", Span::new(start, src.len()))),
Some('"') if ch(j + 1) == Some('"') => {
text.push('"');
j += 2;
}
Some('"') => {
j += 1;
break;
}
Some(c) => {
text.push(c);
j += 1;
}
}
}
out.push(Token { kind: TokenKind::String(text), span: Span::new(start, pos(j)) });
i = j;
}
'\'' => {
let mut text = String::new();
let mut j = i + 1;
loop {
match ch(j) {
None => return Err(LexError::new("unterminated quoted identifier", Span::new(start, src.len()))),
Some('\'') if ch(j + 1) == Some('\'') => {
text.push('\'');
j += 2;
}
Some('\'') => {
j += 1;
break;
}
Some(c) => {
text.push(c);
j += 1;
}
}
}
if text.is_empty() {
return Err(LexError::new("empty quoted identifier", Span::new(start, pos(j))));
}
out.push(Token { kind: TokenKind::QuotedIdent(text), span: Span::new(start, pos(j)) });
i = j;
}
'[' => {
let mut text = String::new();
let mut j = i + 1;
loop {
match ch(j) {
None => return Err(LexError::new("unterminated bracketed identifier", Span::new(start, src.len()))),
Some(']') if ch(j + 1) == Some(']') => {
text.push(']');
j += 2;
}
Some(']') => {
j += 1;
break;
}
Some(c) => {
text.push(c);
j += 1;
}
}
}
if text.is_empty() {
return Err(LexError::new("empty bracketed identifier", Span::new(start, pos(j))));
}
out.push(Token { kind: TokenKind::BracketIdent(text), span: Span::new(start, pos(j)) });
i = j;
}
'0'..='9' | '.' if c != '.' || ch(i + 1).is_some_and(|d| d.is_ascii_digit()) => {
let mut j = i;
let mut text = String::new();
// A digit-only literal is an Integer; a decimal point or exponent makes it a
// Decimal. The sign is always a unary operator, never part of the token.
let mut is_decimal = c == '.';
if c == '.' {
text.push_str("0.");
j += 1;
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
if let Some(d) = ch(j) {
text.push(d);
}
j += 1;
}
} else {
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
if let Some(d) = ch(j) {
text.push(d);
}
j += 1;
}
if ch(j) == Some('.') {
is_decimal = true;
text.push('.');
j += 1;
let fraction = j;
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
if let Some(d) = ch(j) {
text.push(d);
}
j += 1;
}
if j == fraction {
// `1.` / `1.e3`: keep the literal parseable.
text.push('0');
}
}
}
if matches!(ch(j), Some('e' | 'E')) {
is_decimal = true;
text.push('e');
j += 1;
if matches!(ch(j), Some('+' | '-')) {
if let Some(sign) = ch(j) {
text.push(sign);
}
j += 1;
}
let digits = j;
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
if let Some(d) = ch(j) {
text.push(d);
}
j += 1;
}
if j == digits {
return Err(LexError::new("numeric literal has no exponent digits", Span::new(start, pos(j))));
}
}
if ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
return Err(LexError::new("invalid numeric literal", Span::new(start, pos(j + 1))));
}
let span = Span::new(start, pos(j));
let kind = if is_decimal {
let value = text.parse::<f64>().map_err(|_| LexError::new("invalid numeric literal", span))?;
if !value.is_finite() {
return Err(LexError::new("decimal literal is out of range", span));
}
TokenKind::Decimal(value)
} else {
let value =
text.parse::<i64>().map_err(|_| LexError::new("integer literal is out of range for a 64-bit signed integer", span))?;
TokenKind::Integer(value)
};
out.push(Token { kind, span });
i = j;
}
c if c.is_alphabetic() || c == '_' => {
let mut text = String::new();
let mut j = i;
while ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
if let Some(c) = ch(j) {
text.push(c);
}
j += 1;
}
// `dt` immediately followed by a double-quoted string is a date/time literal.
// Whitespace between the prefix and the quote is not allowed, so `dt "..."` is
// two tokens and fails to parse. The prefix is case-insensitive like other DAX
// keywords; the printer canonicalises it to lowercase `dt`.
if text.eq_ignore_ascii_case("dt") && ch(j) == Some('"') {
let mut content = String::new();
let mut k = j + 1;
loop {
match ch(k) {
None => {
return Err(LexError::new("unterminated date/time literal", Span::new(start, src.len())));
}
Some('"') => {
k += 1;
break;
}
Some(c) => {
content.push(c);
k += 1;
}
}
}
let span = Span::new(start, pos(k));
let value = parse_datetime_literal(&content).map_err(|message| LexError::new(message, span))?;
out.push(Token { kind: TokenKind::DateTime(value), span });
i = k;
continue;
}
let kind = if text.eq_ignore_ascii_case("NOT") {
TokenKind::Not
} else if text.eq_ignore_ascii_case("IN") {
TokenKind::In
} else if text.eq_ignore_ascii_case("EVALUATE") {
TokenKind::Evaluate
} else {
TokenKind::Ident(text)
};
out.push(Token { kind, span: Span::new(start, pos(j)) });
i = j;
}
'+' => {
out.push(Token { kind: TokenKind::Plus, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'-' => {
out.push(Token { kind: TokenKind::Minus, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'*' => {
out.push(Token { kind: TokenKind::Star, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'/' => {
out.push(Token { kind: TokenKind::Slash, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'^' => {
out.push(Token { kind: TokenKind::Caret, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'&' if ch(i + 1) == Some('&') => {
out.push(Token { kind: TokenKind::AndAnd, span: Span::new(start, pos(i + 2)) });
i += 2;
}
'&' => {
out.push(Token { kind: TokenKind::Amp, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'|' if ch(i + 1) == Some('|') => {
out.push(Token { kind: TokenKind::OrOr, span: Span::new(start, pos(i + 2)) });
i += 2;
}
'|' => return Err(LexError::new("unexpected `|`; the DAX logical OR operator is `||`", Span::new(start, pos(i + 1)))),
'=' if ch(i + 1) == Some('=') => {
out.push(Token { kind: TokenKind::StrictEq, span: Span::new(start, pos(i + 2)) });
i += 2;
}
'=' if ch(i + 1) == Some('>') => {
out.push(Token { kind: TokenKind::Arrow, span: Span::new(start, pos(i + 2)) });
i += 2;
}
'=' => {
out.push(Token { kind: TokenKind::Eq, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'<' if ch(i + 1) == Some('>') => {
out.push(Token { kind: TokenKind::NotEq, span: Span::new(start, pos(i + 2)) });
i += 2;
}
'<' if ch(i + 1) == Some('=') => {
out.push(Token { kind: TokenKind::Le, span: Span::new(start, pos(i + 2)) });
i += 2;
}
'<' => {
out.push(Token { kind: TokenKind::Lt, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'>' if ch(i + 1) == Some('=') => {
out.push(Token { kind: TokenKind::Ge, span: Span::new(start, pos(i + 2)) });
i += 2;
}
'>' => {
out.push(Token { kind: TokenKind::Gt, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'(' => {
out.push(Token { kind: TokenKind::LParen, span: Span::new(start, pos(i + 1)) });
i += 1;
}
')' => {
out.push(Token { kind: TokenKind::RParen, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'{' => {
out.push(Token { kind: TokenKind::LBrace, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'}' => {
out.push(Token { kind: TokenKind::RBrace, span: Span::new(start, pos(i + 1)) });
i += 1;
}
',' => {
out.push(Token { kind: TokenKind::Comma, span: Span::new(start, pos(i + 1)) });
i += 1;
}
':' => {
out.push(Token { kind: TokenKind::Colon, span: Span::new(start, pos(i + 1)) });
i += 1;
}
';' => {
out.push(Token { kind: TokenKind::Semicolon, span: Span::new(start, pos(i + 1)) });
i += 1;
}
'@' => {
let mut text = String::new();
let mut j = i + 1;
while ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
if let Some(c) = ch(j) {
text.push(c);
}
j += 1;
}
if text.is_empty() {
return Err(LexError::new("expected a parameter name after `@`", Span::new(start, pos(j))));
}
out.push(Token { kind: TokenKind::AtName(text), span: Span::new(start, pos(j)) });
i = j;
}
other => {
return Err(LexError::new(format!("unexpected character `{other}`"), Span::new(start, pos(i + 1))));
}
}
}
out.push(Token { kind: TokenKind::Eof, span: Span::new(src.len(), src.len()) });
Ok(out)
}
/// Validates the content of a `dt"..."` literal and splits it into components.
///
/// Accepted forms are `YYYY-MM-DD`, `YYYY-MM-DDThh:mm:ss` and `YYYY-MM-DD hh:mm:ss`. Date and
/// time components may be unpadded (`dt"2015-1-9T2:3:0"`), matching Microsoft's documented
/// example. Timezone offsets, fractional seconds, time-only values and invalid calendar dates
/// are rejected with a lexer error. The `dt` prefix itself is matched by the caller.
fn parse_datetime_literal(text: &str) -> Result<DateTimeLiteral, String> {
let (date, time) = if let Some((date, time)) = text.split_once('T') {
(date, Some(time))
} else if let Some((date, time)) = text.split_once(' ') {
(date, Some(time))
} else {
(text, None)
};
let (year, month, day) = parse_date(date)?;
let (hour, minute, second) = match time {
Some(time) => parse_time(time)?,
None => (0, 0, 0),
};
Ok(DateTimeLiteral { year, month, day, hour, minute, second, has_time: time.is_some() })
}
fn parse_date(text: &str) -> Result<(u32, u32, u32), String> {
let mut parts = text.split('-');
let year_text = parts.next().unwrap_or_default();
let month_text = parts.next().unwrap_or_default();
let day_text = parts.next().unwrap_or_default();
if parts.next().is_some() || year_text.is_empty() || month_text.is_empty() || day_text.is_empty() {
return Err("invalid date/time literal: the date must be YYYY-MM-DD".into());
}
if year_text.len() != 4 || month_text.len() > 2 || day_text.len() > 2 {
return Err("invalid date/time literal: the date must be YYYY-MM-DD (unpadded month and day are allowed)".into());
}
let year = parse_component(year_text, "year")?;
let month = parse_component(month_text, "month")?;
let day = parse_component(day_text, "day")?;
if year == 0 || year > 9999 {
return Err("invalid date/time literal: the year must be between 0001 and 9999".into());
}
if !(1..=12).contains(&month) {
return Err("invalid date/time literal: the month must be between 1 and 12".into());
}
// A date exists exactly when chrono can build it: that rejects day 0, 31 April and 29 February
// of a common year without hand-written month lengths or leap-year math (AGENTS.md).
if NaiveDate::from_ymd_opt(year as i32, month, day).is_none() {
return Err("invalid date/time literal: the date is not a valid calendar date".into());
}
Ok((year, month, day))
}
fn parse_time(text: &str) -> Result<(u32, u32, u32), String> {
let mut parts = text.split(':');
let hour_text = parts.next().unwrap_or_default();
let minute_text = parts.next().unwrap_or_default();
let second_text = parts.next().unwrap_or_default();
if parts.next().is_some() || hour_text.is_empty() || minute_text.is_empty() || second_text.is_empty() {
return Err("invalid date/time literal: the time must be hh:mm:ss".into());
}
if hour_text.len() > 2 || minute_text.len() > 2 || second_text.len() > 2 {
return Err("invalid date/time literal: the time must be hh:mm:ss without fractional seconds".into());
}
let hour = parse_component(hour_text, "hour")?;
let minute = parse_component(minute_text, "minute")?;
let second = parse_component(second_text, "second")?;
if hour > 23 || minute > 59 || second > 59 {
return Err("invalid date/time literal: the time is out of range".into());
}
Ok((hour, minute, second))
}
/// Parses one date/time component. Rejects signs, whitespace, fractional parts and everything
/// else that is not an ASCII digit, so timezone offsets (`Z`, `+02:00`) and fractional seconds
/// cannot slip through.
fn parse_component(text: &str, unit: &str) -> Result<u32, String> {
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(format!("invalid date/time literal: the {unit} must be digits"));
}
text.parse::<u32>().map_err(|_| format!("invalid date/time literal: the {unit} is out of range"))
}
+64
View File
@@ -0,0 +1,64 @@
//! The DAX language: tokenizer, syntax tree, Pratt parser, canonical printer and static types.
//!
//! This crate covers the DAX expression grammar, the function catalog for every dax.guide category
//! with static call validation, the static type surface (literal classification, inference and the documented
//! operator result tables) and the DAX query statements: `DEFINE` (`MEASURE`, `COLUMN`, `TABLE`,
//! `VAR`, `FUNCTION`, `MPARAMETER`), `EVALUATE`, `ORDER BY`, `START AT`, expression-level
//! `VAR ... RETURN`, and `WITH VISUAL SHAPE` (`AXIS`, `GROUP`, `TOTAL`, `DENSIFY`). It also
//! includes a model evaluator, a columnar model store and a PivotTable renderer. The evaluator materializes the model once into the columnar store and
//! answers filtering, aggregates, `VALUES`/`DISTINCT`, relationship joins and pivot grouping from
//! it; models that cannot be stored losslessly (ragged rows, promoted column types) and functions
//! that need a row context still read the row-based `DataModel`.
//!
//! ```
//! use gridcraft_dax::{parse_expression, print_expression};
//!
//! let expr = parse_expression("1 + 2 * 3")?;
//! assert_eq!(print_expression(&expr), "1 + 2 * 3");
//! # Ok::<(), gridcraft_dax::ParseError>(())
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
pub mod ast;
pub mod binder;
pub mod eval;
pub mod functions;
pub mod integrity;
pub mod lexer;
pub mod model;
pub mod parser;
pub mod pivot;
pub mod pivot_table;
pub mod printer;
pub mod references;
pub mod storage;
pub mod types;
pub mod validate;
pub mod value;
pub use ast::{
Axis, AxisGroup, AxisKind, AxisOrderItem, BinaryOp, Call, ColumnDef, DateTimeLiteral, Define, Definition, Evaluate, Expr, ExprKind, FunctionDef,
FunctionParam, Literal, MParameterDef, MeasureDef, Name, NameRef, NameStyle, OrderItem, ParameterSubtype, ParameterType, PassingMode, Query,
SortDirection, Span, StartValue, TableDef, UnaryOp, VarDecl, VarDef, VisualShape,
};
pub use binder::{BindError, Binder, BoundExpr, BoundMeasure, BoundVariable, bind_formula};
pub use eval::{Evaluator, FilterContext, StorageStats};
pub use functions::{BlankPolicy, FunctionCategory, FunctionFlags, FunctionSpec, Overload, ParamKind, Parameter, ReturnType, catalog, lookup};
pub use integrity::{
Cardinality, IntegrityCheck, IntegrityFinding, IntegrityReport, MAX_REPORTED_CYCLES, MAX_REPORTED_KEYS, MAX_REPORTED_ROWS, RelationshipCheck,
Severity, validate_model,
};
pub use lexer::{LexError, MAX_INPUT_LEN, MAX_QUERY_LEN, Token, TokenKind, tokenize};
pub use model::{DataModel, Measure, ModelColumn, ModelError, ModelTable, Relationship, parse_measure};
pub use parser::{MAX_DEPTH, ParseError, parse_expression, parse_query};
pub use pivot::{PivotError, PivotField, pivot, pivot_cross, pivot_fields};
pub use printer::{print_expression, print_query};
pub use references::{column_ref, implicit_measure_formula, table_ref};
pub use storage::{ColumnFootprint, MIN_ENCODING_SAVING, PackedCodes, SCAN_BATCH_ROWS, StorageFootprint, TableFootprint, ValueRef};
pub use validate::{ValidationError, ValidationErrorKind, validate_call, validate_expression};
pub use value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue};
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod tests;

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