Compare commits

..
Author SHA1 Message Date
skylartaylor 16610b20b1 nightly: fix the launcher, Windows build and profile-probe review findings
- Both Linux launchers dispatch the Launcher's protocol and a bare version query before the
  XDG_DATA_HOME/HOME guard, so neither is refused for a HOME it never reads.
- `nightly.ps1` builds into the `-TargetDir` its archive steps read.
- The writable probe retries on a leftover file with its name and removes only the file it created.
- The planted-record-link test writes at RECORD rather than a sibling name, so it exercises the
  alias it plants.
2026-11-25 01:05:43 +01:00
skylartaylor f0c68d6d2c nightly: read the built commit only from a lower-case version
gate / gate (ubuntu-24.04) failed channel::tests::the_commit_is_read_back_only_from_a_nightly_version:
`commit_for` used `is_ascii_hexdigit`, which also accepts A-F, so `...gABCDEF012345` read back
as a commit although the producer's version pattern is lower-case. The check now takes digits
and a-f only, as the nightly version pattern already requires.
2026-11-25 00:59:42 +01:00
skylartaylor 45d59d1487 nightly: enforce the signing guard and read the whole push mapping
- `nightly_compile_gui` calls `nightly_refuse_signing_env` before cargo, so an exported signing
  key cannot reach the compiler or any dependency build script. The helper existed but no path
  called it.
- The candidate-workflow check reads the whole `push:` mapping by indentation instead of a
  contiguous run of non-empty lines, so a `paths:`/`paths-ignore:` filter after a blank line is
  still rejected; a negative fixture covers that layout.
2026-11-25 00:57:24 +01:00
skylartaylor 2dfba46227 nightly: make the app_dirs tests independent of the host's separator
gate / gate (ubuntu-24.04) and SonarCloud's coverage shard 2 both failed on
`each_platform_keeps_its_published_folder`: it compared a `join`ed path against a literal with
Windows backslashes, so on Linux the function's `C:\\.../GridCraft` never matched. Both
tests now build their expectation with the same `PathBuf::join` on the same base, and the
`cfg!(windows)` home switch is gone, so they hold on either host.
2026-11-25 00:49:14 +01:00
skylartaylor bfc5a35ed7 nightly: pass set_token_root itself to and_then (clippy redundant_closure) 2026-11-25 00:29:55 +01:00
skylartaylor 04198c771d nightly: if-then-else for the imported signing identity (SC2015)
shellcheck reads `A && B || C` as a possible false branch. The identity and keychain
checks are now an explicit `if`, with the same behaviour and message.
2026-11-25 00:29:55 +01:00
skylartaylor c1e55f8d27 Nightly: keep Dylan's callers, fix rustfmt, ship the kit's tar layout
- Put his nightly.yml, nightly-sign.yml and installed signing policy back byte
  for byte (no `false &&`, his five manual actors, his 605d5876 pin), and drop
  our dormant duplicates: nightly-dispatch.yml, the policy template and the
  actionlint waiver that only hid the `queue:` key he removed.
- Adapt nightly-release-tests.py to the enabled pair: no schedule, his exact
  context guards, the release managers in caller and policy, one pin, the
  installed policy's fields and platforms, plus this branch's guards for the
  committed Linux key and the Sonar fixture scope.
- cargo fmt --all (17 hunks in 7 files); clean under rustfmt 1.10 and 1.100.
- Flat nightly tar uses the kit layout: `gridcraft` is the launcher and
  `gridcraft-bin` the GUI it starts, and the launcher never starts itself.
- docs: his go-live doc, one stale sentence corrected, plus a flavor section.
- Drop the unused GRIDCRAFT_CONFIG_DIR stable knob; an empty XDG_CONFIG_HOME
  now falls back to ~/.config.
2026-11-25 00:08:19 +01:00
skylartaylor f59fdf3e84 Linux nightlies: start every format through the flavor's launch profile
Dylan's ports keep the nightly identities but start the GUI directly, and a nightly build
refuses to start without --launch-profile nightly-v1 --profile-root <dir>. Ship the launcher
every Linux nightly format needs, so an installed, extracted or sandboxed nightly never runs
against the stable profile (his remaining re-review items close with it).

- deb/rpm: usr/bin/gridcraft-nightly is a launcher; the GUI moves to
  usr/lib/gridcraft-nightly/gridcraft, which nfpm.yaml carries with mode 0755. A stable stage
  has no such file, so the three-line entry is dropped and the rendered stable nfpm.yaml stays
  byte-identical to his head.
- AppImage: AppRun is a script, not the usr/bin/gridcraft symlink, and usr/bin/gridcraft-nightly
  is installed beside it; the desktop Exec/TryExec name the launcher.
- Arch handoff: nightly-arch-launch.sh passes the profile tokens instead of relocating the four
  XDG folders (the profile holds settings, logs, the control token and the session record).
- Flatpak: bin/gridcraft-nightly is installed and is the manifest's command: and the desktop
  entry's Exec/TryExec. profile_root now accepts that package's own id
  (ai.storyteller.gridcraft.nightly) and still refuses the stable id and every other one.
- plain tarballs: bin/gridcraft-nightly in package.sh's tree and gridcraft-nightly in the flat
  nightly.sh archive, which nightly-archive.py now requires.

The profile root is ${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile in every
format; it sits beside, never inside, the stable rows.

Also from the re-review: the nightly metainfo no longer lists mediatypes and names the launcher
as its binary, the nightly desktop file and metainfo are validated now that the tools are
present, and nightly-common.sh passes GRIDCRAFT_VERSION on the build command as well as
inheriting it and checks the exact identity the binary prints (with the output in the message).
packaging/linux/nightly-linux-launch-tests.py runs the launcher in both moved-tree layouts and
stages deb, tar and AppImage with stub nfpm/appimagetool/strip, so the wrappers are tested
without cargo; nightly-arch-tar-test.sh asserts the launcher argv.

Builds on dylanmtaylor's co-installable Linux packages (#4733, @dylanmtaylor).

skylartaylor <[email protected]>
2026-11-24 23:19:36 +01:00
skylartaylor 6157356c1a Nightly: app-side flavor, Windows and macOS packaging, dormant release callers
Give GridCraft the isolated nightly-v1 channel from the nightlies-lead kit, rebased on
dylanmtaylor's #4733 head: his Linux tar, shared helpers, Arch wrapper and Flatpak/nfpm
changes stay his and are not re-authored here (thanks, Dylan). This commit adds the app
side, Windows and macOS packaging, and the dormant release registration.

App side:
- build.rs selects the channel (GRIDCRAFT_BUILD_CHANNEL), refuses any other value and
  requires the prepared GRIDCRAFT_VERSION for a nightly, which becomes the PE
  ProductVersion and the version the app reports.
- launch_profile.rs implements the Launcher protocol (--launch-profile nightly-v1
  --profile-root <abs> -- files…, separate tokens only) and answers both --version forms
  before any root, log, identity, IPC or window work.
- profile_root.rs fences every stable data root per OS (settings and logs, the control
  token folder, both MSI install folders, the XDG folders plus the system installs and the
  Flatpak row, the four macOS Library rows and the bundle), refuses GRIDCRAFT_CONFIG_DIR,
  an inherited FLATPAK_ID, traversal and alias escapes, and proves the profile writable.
- app_dirs.rs is the single data-root resolver: validated profile, then GRIDCRAFT_CONFIG_DIR,
  then the platform default; ui.json, prefs.json and logs follow it.
- nightly_session.rs keeps a lease and an unclean-exit record, finished in on_exit (the only
  path macOS ⌘Q runs before AppKit ends the process).
- process_identity.rs sets the nightly Windows AUMID before any window; stable never does.
- A nightly skips the updater, the control server (and refuses --control), and the inherited
  control variables; the control-token folder can be pointed at the profile.
- ui-egui gains the channel (app id, name, version, commit, window titles, stable-only
  services), which About, File ▸ Account, window titles and the updater guard use. The
  window keeps a Flatpak package's own id when FLATPAK_ID is set (#4733).
- gridcraft-cli refuses the Launcher profile flags with exit 2.

Packaging: packaging/windows/nightly.ps1 with package.ps1 -Nightly and sign.ps1
-Required/-CheckOnly/-CheckBuildEnvironment; macOS nightly.sh, nightly-lib.sh,
nightly-sign.sh, nightly-verify.sh and nightly_plist.py; the nightly icon set rendered
from a deeper-field vector master by packaging/nightly-icons.py, with provenance. The
Linux tar now stages that icon (one line changed in Dylan's script).

Release: dormant nightly.yml, nightly-sign.yml and nightly-dispatch.yml (literal false &&
everywhere), the v3 policy example with no authority, the stable Linux public key,
actionlint's queue suppression, the packaging-lint source-contract job, sonar.sources
plus the exact fixture scope, and packaging/nightly-release-tests.py. Dylan's enabled
callers, installed policy and shorter docs are superseded so the port lands switched off;
the policy content stays in his branch for the enable PR.

skylartaylor <[email protected]>
2026-11-24 22:45:57 +01:00
Dylan M. Taylor 98641eae37 packaging: port nightly.sh helpers and fix PR review/CI issues 2026-11-24 16:18:22 -05:00
Dylan M. Taylor b665e351c1 fix(nightly): fix CI lint/lockfile and address review comments 2026-11-24 14:21:57 -05:00
Dylan M. Taylorandskylartaylor abc551f88f ci(nightly): enable supervised manual nightly runs
Ported from storytold/photocraft#16594 by Skylar (@skylartaylor), adapted for GridCraft:
- Add .github/nightly-signing-policy.json (v3 policy for storytold/gridcraft, repo ID 1408285582, CI workflow 380135773, Sonar project storytold_gridcraft; producer_workflow_id left null until nightly.yml lands on main)
- Add .github/workflows/nightly.yml and .github/workflows/nightly-sign.yml for supervised manual workflow_dispatch runs pinned to craft-common-actions@605d58766e8f536564da8fc81d3676ac86816dea
- Add docs/nightly-release-preparation.md and packaging/nightly-release-tests.py

Credit: Skylar (@skylartaylor), storytold/photocraft#16594

Co-authored-by: skylartaylor <[email protected]>
2026-11-24 14:14:33 -05:00
Dylan M. Taylor 8007e842b9 packaging(linux): support co-installable nightly packages 2026-11-24 13:33:42 -05:00
474 changed files with 3493 additions and 70479 deletions
+7 -17
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/gridcraft",
"repository_id": 1408285582,
"producer_workflow_id": 429713469,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
@@ -83,9 +83,7 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [
"github-actions[bot]"
],
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -97,15 +95,7 @@
"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",
-2
View File
@@ -9,11 +9,9 @@ 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
@@ -1,71 +0,0 @@
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.')
+8 -25
View File
@@ -1,8 +1,7 @@
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.
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
@@ -23,37 +22,21 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/gridcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
github.ref == 'refs/heads/release' && 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
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: main
app-name: gridcraft
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
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 }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
+6 -7
View File
@@ -1,9 +1,8 @@
name: GridCraft unsigned nightly
# Automated daily nightly builds at 03:30 UTC (plus manual dispatch by reviewed manual actors).
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
schedule:
- cron: '30 3 * * *'
workflow_dispatch:
permissions:
@@ -23,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: main
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
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).
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
-20
View File
@@ -1,20 +0,0 @@
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 }}
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
group: sonarcloud-${{ 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' }}
-68
View File
@@ -1,68 +0,0 @@
name: Workbook print range verification
on:
push:
branches: [verify/gridcraft-print-range-4859]
permissions:
contents: read
env:
CARGO_PROFILE_TEST_DEBUG: 0
CARGO_PROFILE_DEV_DEBUG: 0
CARGO_INCREMENTAL: 0
jobs:
shared:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
repository: storytold/craft-libs
ref: 2ed780c05a40870fe0487b04d74aa0d4d89a18c8
persist-credentials: false
- run: |
set -euo pipefail
cargo test --locked -p craft-pages --lib | tee "$RUNNER_TEMP/shared.txt"
grep -E 'print_page_spans_follow_whole_job_bounds.*ok' "$RUNNER_TEMP/shared.txt"
workbook:
runs-on: ubuntu-24.04
timeout-minutes: 115
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: 1
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev
libgtk-3-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev libasound2-dev xvfb xauth
- name: Resolve all framework dependencies at the verification revision
run: |
set -euo pipefail
old=8fa4db64a9bb943520259ea95331a303ba788f21
new=2ed780c05a40870fe0487b04d74aa0d4d89a18c8
git grep -lz -F "$old" -- Cargo.toml Cargo.lock ':(glob)**/Cargo.toml' | xargs -0 sed -i "s/$old/$new/g"
cargo metadata --format-version 1 > "$RUNNER_TEMP/graph.json"
python3 - "$RUNNER_TEMP/graph.json" "$new" <<'PY'
import json, sys
packages = json.load(open(sys.argv[1]))["packages"]
sources = {p["source"] for p in packages if "github.com/storytold/craft-libs" in (p["source"] or "")}
assert len(sources) == 1 and sources.pop().endswith("#" + sys.argv[2])
assert any(p["name"] == "craft-pages" for p in packages)
PY
- name: Workbook print and PDF output
run: |
set -euo pipefail
cargo test --locked -p gridcraft-engine --lib cmd::print::tests | tee "$RUNNER_TEMP/engine.txt"
grep -E 'a_page_range_prints_its_pages_under_the_whole_jobs_numbers.*ok' "$RUNNER_TEMP/engine.txt"
grep -E 'a_range_prints_instead_of_the_print_area_and_each_area_gets_its_own_pages.*ok' "$RUNNER_TEMP/engine.txt"
- name: Native print window, range selection, submission and PDF export
run: |
set -euo pipefail
xvfb-run -a cargo test --locked -p gridcraft-ui-egui --test it native_print:: -- --test-threads=1 | tee "$RUNNER_TEMP/ui.txt"
grep -E 'each_window_keeps_its_own_page_range.*ok' "$RUNNER_TEMP/ui.txt"
grep -E 'create_pdf_exports_the_page_range_under_it.*ok' "$RUNNER_TEMP/ui.txt"
-1
View File
@@ -81,5 +81,4 @@ 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`.
-1
View File
@@ -13,7 +13,6 @@ 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 |
Generated
+203 -1454
View File
File diff suppressed because it is too large Load Diff
+33 -46
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
[workspace.package]
version = "0.20.0"
version = "0.19.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -16,7 +16,6 @@ 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" }
@@ -31,31 +30,29 @@ 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] }
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
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" }
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" }
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
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" }
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" }
# OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`.
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-pages = { 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" }
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" }
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", 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 = "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" }
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" }
# foundation
thiserror = "2"
@@ -67,11 +64,9 @@ 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.42"
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
quick-xml = "0.41"
zip = { version = "3", 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
@@ -97,15 +92,7 @@ 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 = "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"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -133,18 +120,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 = "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" }
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" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
-29
View File
@@ -324,35 +324,6 @@ 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,
+1 -30
View File
@@ -2,10 +2,9 @@
**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 (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-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-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:
@@ -152,15 +151,10 @@ 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`) |
@@ -171,9 +165,6 @@ 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) |
@@ -193,20 +184,14 @@ 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 |
@@ -224,7 +209,6 @@ 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) |
@@ -297,11 +281,9 @@ 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 |
@@ -314,17 +296,13 @@ 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) |
@@ -337,21 +315,14 @@ 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 |
+1 -8
View File
@@ -65,13 +65,6 @@ 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}"));
@@ -161,7 +154,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, pivot_count(sa), pivot_count(sb));
diff_count(&mut pivots, &name, sa.pivots.len(), sb.pivots.len());
}
let mut names = Diffs::new("names", m);
let name_list = |wb: &Workbook| -> BTreeSet<String> {
+44 -100
View File
@@ -16,8 +16,11 @@ pub(super) const REBUILT_KINDS: [&str; 1] = ["calcchain"];
// ---------------------------------------------------------------- package validation
fn local_name(name: &str) -> &str {
name.rsplit(':').next().unwrap_or(name)
fn local_name(name: &[u8]) -> &[u8] {
match name.iter().rposition(|&b| b == b':') {
Some(i) => name.get(i + 1..).unwrap_or(name),
None => name,
}
}
/// `(element local name, attributes)` for every start/empty element of an XML part.
@@ -38,12 +41,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(_) => a.value.to_string(),
Err(_) => String::from_utf8_lossy(&a.value).into_owned(),
};
(local_name(a.key.as_ref()).to_string(), v)
(String::from_utf8_lossy(local_name(a.key.as_ref())).into_owned(), v)
})
.collect();
out.push((local_name(e.name().as_ref()).to_string(), attrs));
out.push((String::from_utf8_lossy(local_name(e.name().as_ref())).into_owned(), attrs));
}
Ok(Event::Eof) => break,
Ok(_) => {}
@@ -107,20 +110,12 @@ fn resolve_target(source_dir: &str, target: &str) -> String {
type Zip<'a> = zip::ZipArchive<Cursor<&'a [u8]>>;
/// `(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 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()
}
/// 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}"))?;
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}"))?;
let mut buf = Vec::new();
f.take(MAX_XML_PART).read_to_end(&mut buf).map_err(|e| format!("{name}: {e}"))?;
Ok(buf)
@@ -133,8 +128,8 @@ enum PartError {
}
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
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)?;
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)?;
// 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();
@@ -155,10 +150,10 @@ fn read_zip_part_within(zip: &mut Zip<'_>, index: usize, budget: &mut u64) -> Re
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((i, rels)) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, i, &rels)
if let Some(rels) = find("_rels/.rels")
&& let Ok(xml) = read_zip_part(&mut zip, &rels)
&& let Ok(els) = xml_elements(&xml)
&& let Some(target) = els
.iter()
@@ -167,8 +162,8 @@ pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
{
workbook = resolve_target("", target);
}
let Some((i, name)) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, i, &name) else { return false };
let Some(name) = find(&part_key(&workbook)) else { return false };
let Ok(xml) = read_zip_part(&mut zip, &name) else { return false };
xml_elements(&xml)
.ok()
.into_iter()
@@ -182,15 +177,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 = |index: usize, name: &str| read_zip_part(&mut zip, index, name);
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 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((i, n)) => {
for (el, attrs) in xml_elements(&read_part(i, &n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
Some(n) => {
for (el, attrs) in xml_elements(&read_part(&n)?).map_err(|e| format!("[Content_Types].xml: {e}"))? {
match el.as_str() {
"Default" => {
if let Some(x) = attr(&attrs, "Extension") {
@@ -207,9 +202,9 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
}
}
}
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 mut sorted: Vec<&String> = names.iter().collect();
sorted.sort();
for n in &sorted {
let key = part_key(n);
if key == "[content_types].xml" {
continue;
@@ -224,7 +219,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 (i, n) in sorted {
for 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.
@@ -238,7 +233,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(*i, n)?).map_err(|e| format!("{n}: {e}"))? {
for (el, attrs) in xml_elements(&read_part(n)?).map_err(|e| format!("{n}: {e}"))? {
if el != "Relationship" {
continue;
}
@@ -273,17 +268,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, &(usize, String)> = names.iter().map(|e| (part_key(&e.1), e)).collect();
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).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<(usize, &'static str), bool> = HashMap::new();
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
let mut kinds = BTreeMap::new();
for (i, n) in names.iter().filter(|(_, n)| part_key(n).ends_with(".rels")) {
for 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, *i, &mut budget) {
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
Ok(xml) => xml,
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
Err(PartError::Unreadable) => continue,
@@ -297,8 +292,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((index, _)) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, *index, kind, &mut verdicts, &mut budget)
&& let Some(part) = by_key.get(&resolve_target(&src_dir, target).to_ascii_lowercase())
&& !holds_something(&mut zip, part, kind, &mut verdicts, &mut budget)
{
continue;
}
@@ -319,7 +314,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<'_>, index: usize, kind: &str, verdicts: &mut HashMap<(usize, &'static str), bool>, budget: &mut u64) -> bool {
fn holds_something(zip: &mut Zip<'_>, name: &str, kind: &str, verdicts: &mut HashMap<(String, &'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"),
@@ -330,26 +325,26 @@ fn holds_something(zip: &mut Zip<'_>, index: usize, kind: &str, verdicts: &mut H
Some(_) => "shape",
None => "any",
};
if let Some(v) = verdicts.get(&(index, marker)) {
if let Some(v) = verdicts.get(&(name.to_ascii_lowercase(), marker)) {
return *v;
}
let v = holds_something_uncached(zip, index, marker, budget);
verdicts.insert((index, marker), v);
let v = holds_something_uncached(zip, name, marker, budget);
verdicts.insert((name.to_ascii_lowercase(), marker), v);
v
}
fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static str, budget: &mut u64) -> bool {
fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str, budget: &mut u64) -> bool {
use quick_xml::events::Event;
let Ok(f) = zip.by_index(index) else { return true };
let Ok(f) = zip.by_name(name) 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 str> = match marker {
"comment" => Some("comment"),
"shape" => Some("shape"),
let wanted: Option<&'static [u8]> = match marker {
"comment" => Some(b"comment"),
"shape" => Some(b"shape"),
_ => None,
};
let mut buf = Vec::new();
@@ -397,57 +392,6 @@ 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().unwrap().to_string();
let name = f.name().to_string();
let mut body = String::new();
f.read_to_string(&mut body).unwrap();
if let Some(at) = pending.iter().position(|(r, _)| *r == name) {
+1 -4
View File
@@ -187,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 matches!(id, "file.open" | "file.save" | "file.saveAs" | "file.saveBytes")
if id == "file.open"
&& let Ok(value) = &r
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
{
@@ -328,9 +328,6 @@ 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())?;
+2 -2
View File
@@ -18,8 +18,8 @@ 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 = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
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" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
-3
View File
@@ -49,7 +49,6 @@ 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.
@@ -159,7 +158,6 @@ 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() {
@@ -179,7 +177,6 @@ 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) {
+1 -7
View File
@@ -30,11 +30,9 @@ 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 = { workspace = true }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "aa84415bae3b765fef6b7ef42404f66ad1cff9d9" }
craft-update = { workspace = true }
rfd = { workspace = true }
arboard = { workspace = true, features = ["image-data"] }
@@ -45,10 +43,6 @@ 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"
+32 -5
View File
@@ -1,12 +1,24 @@
//! 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.
//! stable build, and a nightly build cannot be talked out of its profile.
use crate::launch_profile::Profile;
use std::ffi::OsString;
pub use craft_nightly::BuildFlavor;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open GridCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable GridCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -24,8 +36,7 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::{BuildFlavor, needs_native_error, version, version_query};
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -34,6 +45,22 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
+172 -84
View File
@@ -1,43 +1,131 @@
//! 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.
//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
//! Stable launches keep their original arguments and directory policy. No environment mutation.
//!
//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with
//! `--profile-root <absolute>` as separate tokens, then `--` and the files. Everything after `--`
//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's
//! `--launch-profile nightly-v1 --profile-root <abs> --version`) is answered by `main` before any
//! of this can create a directory, open a log or start a window.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub use craft_nightly::Profile;
pub const VERSION: &str = "nightly-v1";
/// 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)
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
/// 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();
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
passthrough_args
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
}
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
/// runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
}
#[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;
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
@@ -48,88 +136,88 @@ mod tests {
}
fn nightly() -> Vec<OsString> {
launch_arguments(Path::new(absolute()), &[])
args(&["--launch-profile", VERSION, "--profile-root", 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);
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, 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();
let launch = parse(argv).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"])
);
assert_eq!(launch.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();
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--launch-profile", VERSION]),
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()]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "/one/../two", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).is_err(), "{argv:?}");
assert!(parse(argv.clone()).is_err(), "{argv:?}");
}
assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value");
}
#[test]
fn launcher_version_queries_are_recognized_without_touching_the_profile() {
let spec = profile_root::app_spec();
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
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"])),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "7979", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
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:?}");
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+56 -182
View File
@@ -66,12 +66,13 @@ impl eframe::App for App {
}
self.app.logic(ctx);
self.windows.logic(&mut self.app, ctx);
self.app.close_path(ctx);
if ctx.input(|input| input.viewport().close_requested()) && self.app.printing.busy() {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
}
/// 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.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()) {
@@ -79,8 +80,7 @@ impl eframe::App for App {
}
}
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
gridcraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.windows.show(&mut self.app, ui);
}
fn on_exit(&mut self) {
@@ -214,13 +214,8 @@ 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); 5] = [
("Excel Workbook (.xlsx)", "xlsx"),
("CSV UTF-8 (.csv)", "csv"),
("Web Page (.html)", "html"),
("PDF (.pdf)", "pdf"),
("GridCraft Workbook (.json)", "json"),
];
const TYPES: [(&str, &str); 4] =
[("Excel Workbook (.xlsx)", "xlsx"), ("CSV UTF-8 (.csv)", "csv"), ("Web Page (.html)", "html"), ("PDF (.pdf)", "pdf")];
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}"));
@@ -273,23 +268,14 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
)
}
/// 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.
/// Tell a desktop user why a nightly launch was refused. 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 build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("GridCraft launch profile: {error}");
return;
@@ -309,89 +295,39 @@ fn report_launch_profile_error(error: &str) {
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) {
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window (a dialog
// here would hang a headless runner and fail a Linux build).
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::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())
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
report_launch_profile_error(&error);
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")) {
if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) =
launch_profile::install(early.profile).and_then(|()| 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")
Some(early.args)
}
fn main() -> eframe::Result<()> {
@@ -456,14 +392,34 @@ fn main() -> eframe::Result<()> {
}
// 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) {
if nightly && args.iter().any(|a| a == "--control" || a == "--control-token") {
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);
let mut control_port: Option<u16> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten();
let mut control_token: Option<String> = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten();
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 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
@@ -493,6 +449,7 @@ fn main() -> eframe::Result<()> {
if !nightly {
app.start_update_check();
}
let control_port = control_port;
load_prefs(&mut app);
// Stamp the startup workbook's author from the persisted user name.
if app.session.documents().is_empty() {
@@ -586,7 +543,6 @@ fn main() -> eframe::Result<()> {
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()) {
@@ -659,85 +615,3 @@ 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");
}
}
+10 -12
View File
@@ -1,12 +1,15 @@
//! Desktop spooler adapter. Discovery and submission never run on the UI thread.
use gridcraft_ui_egui::printing::{Destination, Discover, Duplex, Printer, Settings, Submit};
use gridcraft_ui_egui::printing::{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::from).collect();
let printers = craft_print::printers()
.into_iter()
.map(|printer| Printer { name: printer.name, label: printer.description, default: printer.default })
.collect();
let _ = sender.send(printers);
});
receiver
@@ -31,17 +34,12 @@ 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: match settings.destination {
Destination::Printer(name) => Some(name),
_ => None,
},
printer: Some(settings.printer),
copies: settings.copies.clamp(1, 999),
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,
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,
}),
grayscale: settings.grayscale,
scaling: craft_print::Scaling::ShrinkToFit,
+419 -209
View File
@@ -1,91 +1,35 @@
//! 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.
//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the
//! process environment. Every stable place a GridCraft build keeps user state is refused as a
//! nightly root, in both directions, so the two channels can never share a file.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use craft_nightly::AppProfileSpec;
/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`).
const WINDOWS_TOKEN_DIR: &str = ".gridcraft";
/// 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)),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
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"));
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// FreeBSD, the BSDs and anything else have no nightly channel.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
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 ignores_case(self) -> bool {
self != Self::Linux
}
}
@@ -96,6 +40,18 @@ fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// 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> {
@@ -118,201 +74,455 @@ fn canonical_future(path: &Path) -> Result<PathBuf, String> {
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s
// token folder, plus both MSI install folders (`install-policy.wxi`).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("GridCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft"));
roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("GridCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("gridcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.gridcraft"));
// `gridcraft_mcp`'s token folder when no XDG runtime directory is set.
roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/GridCraft"),
library.join("Caches/GridCraft"),
library.join("Caches/ai.storyteller.gridcraft"),
library.join("Preferences/GridCraft"),
library.join("Preferences/ai.storyteller.gridcraft.plist"),
library.join("Saved Application State/ai.storyteller.gridcraft.savedState"),
home.join("Applications/GridCraft.app"),
PathBuf::from("/Applications/GridCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
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)
}
/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at the stable app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// 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")
}
/// The app's own exclusive writable probe: create a file inside the profile, then remove it.
pub fn ensure_writable(root: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// A crashed launch can leave a probe with this name behind: take the next one instead of
// failing, and remove only the file this call created, never someone else's.
loop {
let probe =
root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(_) => return std::fs::remove_file(&probe),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID
{
// `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak
// (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one
// instance may carry a profile. Any other, the stable app's included, could point it at
// another installation's tree; these rows are otherwise native tar/app-bundle launches.
return Err(format!(
"nightly-v1 can only run inside its own Flatpak instance ({}), not {}",
gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
id.to_string_lossy()
));
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect a subfolder elsewhere.
control_directory(&chosen)?;
entries_stay_inside(&chosen)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
control_directory(&confirmed)?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
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 {
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
impl Fixture {
fn new() -> 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)));
std::env::temp_dir().join(format!("gridcraft-profile-policy-{}-{}", 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 }
let home = root.join("home");
let exe = root.join("install/gridcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn path(&self) -> &Path {
&self.root
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for TempDir {
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[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")));
fn every_stable_data_root_is_refused_on_its_own_platform() {
let mut fixture = Fixture::new();
// Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user
// and per-machine install folders and the control-token folder.
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft");
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert!(!stable.exists());
}
#[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")));
assert!(
fixture
.check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly"))
.is_err()
);
assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err());
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}");
assert!(!base.join("ArtCraft/GridCraft").exists());
}
#[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")));
// Linux: the four XDG folders, then the stable Flatpak row and the token folder.
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
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 key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
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();
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused");
// macOS: the four Library rows and the bundle itself.
for suffix in [
"Application Support/GridCraft",
"Caches/GridCraft",
"Preferences/GridCraft",
"Saved Application State/ai.storyteller.gridcraft.savedState",
] {
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}");
}
}
#[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());
fn the_launcher_profile_row_is_accepted_on_every_platform() {
let fixture = Fixture::new();
let data = fixture.root.join("Launcher/nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert_eq!(fixture.check(platform, &data).unwrap(), data);
}
assert!(
fixture
.check(
Platform::Linux,
&PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft")
)
.is_ok(),
"the Launcher's own folder is not GridCraft's install"
);
}
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());
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Control"), platform));
assert!(overlaps(&root.join("Control"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform));
}
}
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_install_folder_of_the_running_build_is_refused() {
let fixture = Fixture::new();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err());
}
}
#[test]
fn mac_fences_the_whole_bundle_not_just_its_macos_folder() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok());
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let mut fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in [
(gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true),
// The stable Flatpak, and a lookalike that only shares the prefix, stay refused.
("ai.storyteller.gridcraft", false),
("ai.storyteller.gridcraft.nightly-v1", false),
("io.github.other.Gridcraft", false),
] {
fixture.env.insert("FLATPAK_ID".into(), id.into());
let result = fixture.check(Platform::Linux, &root);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
}
}
#[test]
fn failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount")));
assert!(result.unwrap_err().contains("not writable"));
assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data");
assert!(!fixture.home().join(".config/gridcraft").exists());
}
#[test]
fn a_file_in_place_of_the_profile_is_refused() {
let fixture = Fixture::new();
let candidate = fixture.root.join("not-a-directory");
std::fs::write(&candidate, b"a file, not a profile").unwrap();
assert!(fixture.check(Platform::Linux, &candidate).is_err());
assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile");
}
#[cfg(unix)]
#[test]
fn profile_entry_aliases_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("ui.json"), b"stable settings").unwrap();
for name in ["ui.json", "logs", "Control", "profile"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = fixture.check_with(Platform::Linux, &private, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-logs")).unwrap();
std::fs::write(private.join("ui.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let fixture = Fixture::new();
let outside = fixture.home().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.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!(fixture.check(Platform::Linux, &private).is_err());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
#[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 fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).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);
fn the_writable_probe_leaves_nothing_behind() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
ensure_writable(&private).unwrap();
assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0);
}
}
+3
View File
@@ -11,4 +11,7 @@ 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,9 +118,3 @@ sync_github_name = true
[people.RockerHX]
sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
[people.alosslessdev]
real_name = "Francisco Herrera"
+8 -71
View File
@@ -18,7 +18,7 @@ mod lambda;
mod reference_fns;
mod special;
use array::{binary_scalar_snapped, map_unary};
use array::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,28 +62,6 @@ 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),
@@ -106,11 +84,6 @@ 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
@@ -332,27 +305,6 @@ 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 {
@@ -439,34 +391,25 @@ 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);
}
Ok(())
let r = self.eval_inner(e);
self.depth -= 1;
r
}
fn eval_inner(&mut self, e: &Expr) -> Ev {
@@ -548,13 +491,7 @@ impl<'h> Evaluator<'h> {
let saved = self.sheet;
// Unqualified references in a name refer to the scope sheet.
self.sheet = scope;
// 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),
};
let r = self.eval(&expr);
self.sheet = saved;
r
}
+11 -32
View File
@@ -22,32 +22,17 @@ impl Agg {
/// What a folded aggregate carries from one value to the next.
#[derive(Default)]
pub(super) struct Acc {
/// 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) sum: 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.add(*n);
self.sum += n;
self.count = self.count.saturating_add(1);
Ok(())
}
@@ -57,12 +42,11 @@ 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.last.map_or(self.sum, |l| gridcraft_core::arith::snap_add(self.sum, l))),
Agg::Sum => Value::number(self.sum),
Agg::Count => Value::number(self.count as f64),
Agg::Average if self.count == 0 => Value::Error(CellError::Div0),
Agg::Average => Value::number(plain / self.count as f64),
Agg::Average => Value::number(self.sum / self.count as f64),
}
}
}
@@ -188,17 +172,6 @@ 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 {
@@ -243,7 +216,13 @@ 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)) => Value::text(gridcraft_core::cap_text(x + &y)),
(Ok(x), Ok(y)) => {
if x.len() + y.len() > 32767 * 4 {
Value::Error(CellError::Value)
} else {
Value::text(x + &y)
}
}
(Err(e), _) | (_, Err(e)) => Value::Error(e),
},
BinOp::Eq => Value::Bool(compare(a, b) == Equal),
+12 -24
View File
@@ -5,17 +5,6 @@ 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),
@@ -413,13 +402,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() {
// 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)
// 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)
{
acc.add_range_sum(0.0, count);
acc.sum = sum;
acc.count = acc.count.saturating_add(count);
return Ok(());
}
// Folded without building an array, but still walked: the part inside the used
@@ -444,21 +433,20 @@ impl<'h> Evaluator<'h> {
self.aggregate_value(kind, value, true, acc)
}
/// 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.
/// 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`).
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(count) = gridcraft_functions::lookup("COUNT") else {
let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), 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::numbers(&args) {
Ok(ns) => ns.into_iter().for_each(|n| acc.add(n)),
Err(e) => return Err(err(e)),
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)),
}
}
if kind != Agg::Sum {
+4 -88
View File
@@ -1,26 +1,17 @@
use super::MAX_LAMBDA_CALLS;
use super::array::{broadcast_len, single};
use super::special::is_special;
use super::{Array, BinOp, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, 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(err(CellError::Value));
return err(CellError::Value);
}
let mut bound = Vec::with_capacity(l.params.len());
for (i, p) in l.params.iter().enumerate() {
@@ -30,56 +21,7 @@ impl<'h> Evaluator<'h> {
};
bound.push((p.clone(), v));
}
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),
}
self.call_lambda_values(l, bound)
}
pub(super) fn call_lambda_values(&mut self, l: &Lambda, bound: Vec<(String, Ev)>) -> Ev {
@@ -96,33 +38,7 @@ impl<'h> Evaluator<'h> {
self.calls += 1;
let saved = std::mem::replace(&mut self.env, l.env.clone());
self.env.extend(bound);
// 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) };
}
}
};
let r = self.eval(&l.body);
self.env = saved;
self.calls -= 1;
r
+1 -1
View File
@@ -195,7 +195,7 @@ impl Precedents<'_> {
}
}
pub(super) fn is_special(n: &str) -> bool {
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, evaluate_expr, now_serial};
pub use recalc::{Bounded, Calc, Key, evaluate, evaluate_bounded, now_serial};
#[cfg(test)]
mod tests;
+3 -14
View File
@@ -718,7 +718,7 @@ impl Calc {
} else {
Vec::new()
};
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing, array.data.len());
let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing);
if !blocked {
for (o, r) in outranked {
for c in r.iter() {
@@ -785,7 +785,6 @@ fn spill_is_blocked(
range: RangeRef,
end: CellRef,
standing: &Standing,
array_len: usize,
) -> bool {
let outranked = |cell: CellRef| {
sheet
@@ -797,7 +796,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))
|| (array_len > 1 && sheet.tables.iter().any(|table| table.range.contains(anchor.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) {
@@ -825,21 +824,11 @@ 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);
if root { ev.value_root(expr) } else { ev.value(expr) }
ev.value(expr)
}
/// What [`evaluate_bounded`] found: the formula's reference (not read), its value, or that it ran
+4 -5
View File
@@ -162,8 +162,7 @@ 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 (a one-value result is shown
/// there, as in Excel), or its area runs off the sheet,
/// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet,
/// overlaps merged cells, holds other cells, or 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.
@@ -189,7 +188,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))
|| (a.data.len() > 1 && sh.tables.iter().any(|t| t.range.contains(anchor)))
|| 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))
}
@@ -201,7 +200,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))
&& (arr.data.len() <= 1 || !sheet.tables.iter().any(|t| t.range.contains(anchor)))
&& !sheet.tables.iter().any(|t| t.range.contains(anchor))
&& range
.iter()
.enumerate()
@@ -332,7 +331,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_root(&expr)
ev.value(&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() {
+7 -644
View File
@@ -820,42 +820,6 @@ 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();
@@ -1217,67 +1181,17 @@ fn a_recursive_lambda_stops_at_the_same_call_on_any_stack_size() {
comment: String::new(),
hidden: false,
});
// 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.
// F(F,n) 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(5459), tail(5460), wrapped(69), wrapped(70), "=CNT(131)".to_string()].map(|f| crate::evaluate(&wb, 0, c("B1"), &f))
[tail(139), tail(140), 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::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!(small, [Value::Number(0.0), Value::Error(CellError::Num), Value::Number(69.0), Value::Error(CellError::Num), Value::Number(131.0)]);
assert_eq!(run(64 << 20), small);
}
@@ -1718,478 +1632,6 @@ 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();
@@ -2593,65 +2035,6 @@ 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.
@@ -3234,19 +2617,6 @@ 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();
@@ -3510,17 +2880,13 @@ 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 nums, mut count, mut error) = (Vec::new(), 0u64, None);
if let Some(l) = *lead {
nums.push(l);
count += 1;
}
let (mut sum, mut count, mut error) = (lead.unwrap_or(0.0), u64::from(lead.is_some()), None);
for &(r0, c0, r1, c1) in blocks {
for r in r0..=r1 {
for col in c0..=c1 {
match sh.value(CellRef::new(r, col)) {
Value::Number(n) => {
nums.push(n);
sum += n;
count += 1;
}
Value::Error(e) if *f != "COUNT" => error = error.or(Some(e)),
@@ -3529,15 +2895,12 @@ 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(gridcraft_core::arith::sum_snapped(&nums)),
(_, "SUM") => Value::number(sum),
(_, "COUNT") => Value::number(count as f64),
(_, _) if count == 0 => Value::Error(CellError::Div0),
_ => Value::number(plain / count as f64),
_ => Value::number(sum / count as f64),
};
let got = sh.value(*cell);
let same = match (&got, &want) {
@@ -1,17 +0,0 @@
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");
}
}
+15 -42
View File
@@ -16,7 +16,6 @@ enum Fam {
Col100,
Line,
LineStack,
Line100,
Area,
AreaStack,
Area100,
@@ -32,7 +31,6 @@ 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,
@@ -42,7 +40,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::Line100 | Fam::Area100)
matches!(f, Fam::Col100 | Fam::Area100)
}
fn is_col(f: Fam) -> bool {
@@ -50,21 +48,7 @@ fn is_col(f: Fam) -> bool {
}
fn is_line(f: Fam) -> bool {
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,
}
matches!(f, Fam::Line | Fam::LineStack)
}
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
@@ -80,7 +64,6 @@ 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 }
}
@@ -88,7 +71,6 @@ 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);
@@ -123,15 +105,13 @@ struct BarSink {
bw: f32,
horizontal: bool,
color: Rgba,
stroke: Option<(Rgba, f32)>,
nslots: f32,
k: f32,
}
impl BarSink {
/// 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 }
fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self {
BarSink { run: None, bw, horizontal, color, nslots, k }
}
/// Start of this series' slot along the category axis, for the category centered at `c`.
fn pos(&self, c: f32) -> f32 {
@@ -151,10 +131,11 @@ impl BarSink {
let pos = self.pos(c);
let band = self.band();
if !merge {
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);
if self.horizontal {
ctx.rect(lo, pos, len, self.bw, self.color, None);
} else {
ctx.rect(pos, lo, self.bw, len, self.color, None);
}
return;
}
match &mut self.run {
@@ -166,7 +147,6 @@ 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 {
@@ -176,7 +156,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, lines and areas stack apart).
// Totals for 100% stacking, per axis and family (100% columns and 100% 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);
@@ -207,7 +187,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::Line100 | Fam::AreaStack | Fam::Area100);
let stacked = matches!(fam, Fam::ColStack | Fam::Col100 | Fam::LineStack | Fam::AreaStack | Fam::Area100);
let key = (a, fam);
let si = if stacked {
match stacks.iter().position(|(k, _, _)| *k == key) {
@@ -236,7 +216,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 is_100(fam) { share(key, j, v) } else { v };
let v = if fam == Fam::Area100 { share(key, j, v) } else { v };
pos.get_mut(j).map(|acc| {
let base = *acc;
*acc = clean(*acc + v);
@@ -307,12 +287,6 @@ 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 {
@@ -411,8 +385,7 @@ 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 stroke = (chart.style == 9).then_some((WHITE, 1.0));
let mut sink = BarSink::new(bw, horizontal, s.color, stroke, nslots, k);
let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k);
for (j, sp) in row.iter().enumerate() {
let Some((b, t)) = sp else { continue };
let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc));
@@ -449,9 +422,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, line_style_width(chart.style), s.smooth.then_some(plot));
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
if has_markers(k) && cw >= 3.0 {
if k == ChartKind::LineMarkers && cw >= 3.0 {
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
}
if labels_on {
+2 -4
View File
@@ -57,10 +57,8 @@ 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::LineStacked100 | ChartKind::Radar | ChartKind::ScatterLines => {
Swatch::Line
}
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked | ChartKind::Radar | ChartKind::ScatterLines => Swatch::Line,
ChartKind::LineMarkers => 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 | ChartKind::LineStacked100 => Swatch::Line,
ChartKind::LineMarkers | ChartKind::LineStacked100Markers => Swatch::LineMarker,
ChartKind::Line | ChartKind::LineStacked => Swatch::Line,
ChartKind::LineMarkers => Swatch::LineMarker,
_ => Swatch::Box,
};
draw_swatch(ctx, swatch, x0 + 4.0, y, 7.0, series.color);
+11 -90
View File
@@ -39,28 +39,6 @@ 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()
@@ -382,7 +360,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, innermost: bool) -> (Vec<String>, Vec<Vec<String>>) {
fn category_table(wb: &Workbook, sheet: usize, formula: &str, values: &str, limit: usize) -> (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
@@ -441,21 +419,12 @@ 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 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 {
let outer = levels.outer as usize;
if levels.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
@@ -492,12 +461,8 @@ 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(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES)));
let color =
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
let kind = 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.
@@ -509,7 +474,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, s.innermost_categories);
let (mut c, outer) = category_table(wb, sheet, f, &s.values, limit);
c.truncate(limit);
if !c.is_empty() {
categories = Some(c);
@@ -537,59 +502,15 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
secondary: s.secondary,
smooth: s.smooth,
trendlines,
number_format: match &s.number_format {
Some(code) if s.values.trim_start().starts_with('{') => code.clone(),
_ => ref_format(wb, sheet, &s.values),
},
number_format: 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 = 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))
};
let palette = 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;
@@ -600,7 +521,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, false);
let (texts, _) = super::category_table(&wb, 0, r#"=IF(SEQUENCE(100000),REPT("x",32767))"#, "", super::MAX_POINTS);
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);
@@ -623,7 +544,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, false);
let (inner, outer) = super::category_table(&wb, 0, "=A1:E8000", "", super::MAX_POINTS);
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));
+1 -345
View File
@@ -8,7 +8,7 @@ use crate::*;
mod budget;
mod data_table;
const ALL_KINDS: [ChartKind; 28] = [
const ALL_KINDS: [ChartKind; 26] = [
ChartKind::ColumnClustered,
ChartKind::ColumnStacked,
ChartKind::ColumnStacked100,
@@ -18,8 +18,6 @@ const ALL_KINDS: [ChartKind; 28] = [
ChartKind::Line,
ChartKind::LineMarkers,
ChartKind::LineStacked,
ChartKind::LineStacked100,
ChartKind::LineStacked100Markers,
ChartKind::Pie,
ChartKind::Doughnut,
ChartKind::Area,
@@ -551,9 +549,6 @@ 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,
@@ -566,8 +561,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: Some("Literal".into()),
@@ -580,8 +573,6 @@ 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);
@@ -601,7 +592,6 @@ 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);
@@ -622,8 +612,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
Series {
name: None,
@@ -636,8 +624,6 @@ fn resolve_from_workbook() {
quartiles: Default::default(),
smooth: false,
trendlines: Vec::new(),
number_format: None,
innermost_categories: false,
},
];
let d = resolve(&wb, 0, &c);
@@ -655,8 +641,6 @@ 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));
@@ -675,8 +659,6 @@ 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);
@@ -1382,8 +1364,6 @@ 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)];
@@ -1439,47 +1419,6 @@ 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,
@@ -1552,62 +1491,6 @@ 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", "", ""];
@@ -1682,22 +1565,6 @@ 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;
@@ -1743,7 +1610,6 @@ 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
@@ -1775,13 +1641,11 @@ 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
@@ -1813,13 +1677,11 @@ 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();
@@ -1836,8 +1698,6 @@ fn volatile_series_formulas_are_detected() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
@@ -1852,7 +1712,6 @@ 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| {
@@ -1868,8 +1727,6 @@ fn volatile_defined_names_are_followed() {
smooth: false,
quartiles: Default::default(),
trendlines: vec![],
innermost_categories: false,
number_format: None,
});
c
};
@@ -1917,204 +1774,3 @@ 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,32 +148,3 @@ 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,27 +123,11 @@ 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)) }
@@ -353,19 +337,6 @@ 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
@@ -1,71 +0,0 @@
//! 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,43 +162,6 @@ 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) {
@@ -421,32 +384,4 @@ 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);
}
}
+1 -2
View File
@@ -4,7 +4,6 @@
#![forbid(unsafe_code)]
pub mod addr;
pub mod arith;
pub mod color;
pub mod date;
pub mod parse;
@@ -17,4 +16,4 @@ pub use addr::{
};
pub use date::DateSystem;
pub use region::Region;
pub use value::{Array, CellError, MAX_TEXT_CHARS, Value, cap_text, cap_value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
pub use value::{Array, CellError, Value, compare, compare_numbers, compare_text, number_to_text, sort_compare};
-26
View File
@@ -49,19 +49,6 @@ 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.
@@ -590,19 +577,6 @@ 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,10 +103,6 @@ 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,
@@ -212,23 +208,6 @@ 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) }
@@ -455,16 +434,12 @@ 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),
}
}
@@ -522,56 +497,10 @@ 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");
@@ -651,16 +580,6 @@ 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);
@@ -856,19 +775,6 @@ 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
@@ -1,35 +0,0 @@
[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
@@ -1,430 +0,0 @@
# 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
@@ -1,69 +0,0 @@
//! 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
@@ -1,653 +0,0 @@
//! 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
@@ -1,425 +0,0 @@
//! 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
@@ -1,38 +0,0 @@
//! 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
@@ -1,71 +0,0 @@
//! 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
@@ -1,765 +0,0 @@
//! 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
@@ -1,728 +0,0 @@
//! 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
@@ -1,366 +0,0 @@
//! 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
@@ -1,561 +0,0 @@
//! 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
@@ -1,993 +0,0 @@
//! 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
@@ -1,229 +0,0 @@
//! 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
@@ -1,677 +0,0 @@
//! 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
@@ -1,298 +0,0 @@
//! 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
@@ -1,107 +0,0 @@
//! 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
@@ -1,107 +0,0 @@
//! 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
@@ -1,584 +0,0 @@
//! 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] )"],
),
];
@@ -1,641 +0,0 @@
//! 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
@@ -1,433 +0,0 @@
//! 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] )"],
),
];
@@ -1,716 +0,0 @@
//! 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\" )",
],
),
];
@@ -1,295 +0,0 @@
//! 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
@@ -1,553 +0,0 @@
//! 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
@@ -1,64 +0,0 @@
//! 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;
-371
View File
@@ -1,371 +0,0 @@
//! Tabular data-model metadata: tables, columns, relationships and measures.
//!
//! This is the binder/evaluator's model view. It deliberately does not implement XLSX storage:
//! callers load the metadata from JSON or from a workbook adapter and parse the measure formulas
//! with [`DataModel::parse_formulas`]. Rows are not part of this layer; the evaluator supplies
//! table values.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::value::Scalar;
use crate::{Expr, ParseError, parse_expression};
/// A table in the model. Column order is preserved because `RELATEDTABLE`, `ROW` and table
/// constructors expose it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModelTable {
pub name: String,
#[serde(default)]
pub columns: Vec<ModelColumn>,
/// Optional inline rows. Workbook adapters can fill these; the metadata-only binder ignores
/// them. Each row has one scalar per column, in column order.
#[serde(default)]
pub rows: Vec<Vec<Scalar>>,
}
/// A model column. `data_type` is the model's declared type name (`Int64`, `Double`, `String`,
/// `DateTime`, `Boolean`, `Decimal`, ...); it is metadata, not a parsed [`crate::types::DataType`],
/// because model type names and DAX expression types are not the same vocabulary.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelColumn {
pub name: String,
#[serde(default)]
pub data_type: Option<String>,
}
/// Model metadata the binder does not need: hidden columns, the marked date column and each
/// column's default summarization. It travels inside the same model JSON document, on the table
/// and column objects (`"date_column"`, `"hidden"`, `"summarize_by"`), so a model stays one file;
/// the engine reads and validates it at the model boundary (`dataModel.load`) and reports it from
/// `dataModel.status`.
///
/// The type doubles as the loader: unknown document keys (`rows`, `data_type`, `relationships`,
/// `measures`, ...) are ignored, so a document written before these fields existed loads with
/// every field at its default.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ModelMetadata {
pub tables: Vec<TableMetadata>,
}
/// One table's metadata slice of a model document.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct TableMetadata {
pub name: String,
/// The column marked as this table's date column, in the model's spelling.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_column: Option<String>,
pub columns: Vec<ColumnMetadata>,
}
/// One column's metadata slice of a model document.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ColumnMetadata {
pub name: String,
/// Hidden from the Data View and the field list (`dataModel.setColumnHidden`). Model
/// metadata, as in Excel; the window's "Show Hidden" toggle is only a view setting.
#[serde(skip_serializing_if = "is_false")]
pub hidden: bool,
/// Excel's "Summarize By" (`Sum`, `Average`, `Count`, `Min`, `Max`, `None`), canonicalized.
/// Absent falls back to the type default: numbers sum, everything else counts.
#[serde(skip_serializing_if = "Option::is_none")]
pub summarize_by: Option<String>,
}
/// The canonical spelling of a `Summarize By` name, or `None` when it is not one. Names match
/// case-insensitively and ignore spaces, hyphens and underscores, so `"do not summarize"`,
/// `"DoNotSummarize"` and `"none"` all mean `None`.
pub fn summarize_by_name(name: &str) -> Option<&'static str> {
let key: String = name.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).collect::<String>().to_ascii_lowercase();
match key.as_str() {
"sum" => Some("Sum"),
"average" | "avg" => Some("Average"),
"count" => Some("Count"),
"min" | "minimum" => Some("Min"),
"max" | "maximum" => Some("Max"),
"none" | "donotsummarize" => Some("None"),
_ => None,
}
}
/// Whether a serde field should be left out of the serialized JSON (its default).
fn is_false(value: &bool) -> bool {
!*value
}
impl ModelMetadata {
/// Parses and validates the metadata of a model JSON document.
///
/// The type itself is the loader: unknown document keys (`rows`, `data_type`,
/// `relationships`, `measures`, ...) are ignored, so a document written before the metadata
/// fields existed yields every table and column with default metadata.
pub fn from_model_json(text: &str) -> Result<ModelMetadata, ModelError> {
let mut metadata: ModelMetadata = serde_json::from_str(text).map_err(|error| ModelError::new(format!("invalid model JSON: {error}")))?;
metadata.validate()?;
Ok(metadata)
}
/// Canonicalizes the names and rejects unknown summarizations and a date column that is not
/// one of its table's columns. Duplicate table/column names are the [`DataModel`]'s check;
/// they are rejected here too so a document cannot produce an ambiguous lookup.
pub fn validate(&mut self) -> Result<(), ModelError> {
let mut tables = BTreeMap::new();
for table in &mut self.tables {
if tables.insert(table.name.to_ascii_lowercase(), ()).is_some() {
return Err(ModelError::new(format!("duplicate model table `{}`", table.name)));
}
let mut columns = BTreeMap::new();
for column in &mut table.columns {
if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() {
return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name)));
}
if let Some(name) = column.summarize_by.clone() {
let Some(canonical) = summarize_by_name(&name) else {
return Err(ModelError::new(format!("column `{}` has unknown summarization `{name}`", column.name)));
};
column.summarize_by = Some(canonical.to_string());
}
}
if let Some(date) = table.date_column.clone() {
let Some(column) = table.columns.iter().find(|column| column.name.eq_ignore_ascii_case(&date)) else {
return Err(ModelError::new(format!("table `{}` marks unknown column `{date}` as its date column", table.name)));
};
table.date_column = Some(column.name.clone());
}
}
Ok(())
}
/// A table's metadata, matching names case-insensitively.
pub fn table(&self, name: &str) -> Option<&TableMetadata> {
self.tables.iter().find(|table| table.name.eq_ignore_ascii_case(name))
}
/// A table's metadata for editing.
pub fn table_mut(&mut self, name: &str) -> Option<&mut TableMetadata> {
self.tables.iter_mut().find(|table| table.name.eq_ignore_ascii_case(name))
}
/// A column's metadata, matching table and column names case-insensitively.
pub fn column(&self, table: &str, column: &str) -> Option<&ColumnMetadata> {
self.table(table)?.columns.iter().find(|entry| entry.name.eq_ignore_ascii_case(column))
}
/// A column's metadata for editing.
pub fn column_mut(&mut self, table: &str, column: &str) -> Option<&mut ColumnMetadata> {
let table = self.table_mut(table)?;
table.columns.iter_mut().find(|entry| entry.name.eq_ignore_ascii_case(column))
}
}
/// A single-column relationship between two model tables.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Relationship {
pub from_table: String,
pub from_column: String,
pub to_table: String,
pub to_column: String,
/// `true` when the relationship filters in both directions.
#[serde(default)]
pub bidirectional: bool,
/// Inactive relationships can be activated by `USERELATIONSHIP`.
#[serde(default)]
pub inactive: bool,
}
/// A measure definition. The formula is DAX text; [`DataModel::parse_formulas`] parses it into
/// [`Measure::expr`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Measure {
pub name: String,
pub formula: String,
/// The home table, used by `COUNTROWS()` without an argument and for field-list placement.
#[serde(default)]
pub table: Option<String>,
#[serde(default)]
pub format: Option<String>,
#[serde(skip)]
pub expr: Option<Expr>,
}
/// A model definition loaded from JSON or another workbook adapter.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct DataModel {
#[serde(default)]
pub tables: Vec<ModelTable>,
#[serde(default)]
pub relationships: Vec<Relationship>,
#[serde(default)]
pub measures: Vec<Measure>,
}
/// A metadata or formula error found while preparing a model for binding.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("{message}")]
pub struct ModelError {
pub message: String,
}
impl ModelError {
fn new(message: impl Into<String>) -> Self {
ModelError { message: message.into() }
}
}
impl DataModel {
/// Parses every measure formula and validates table/column/relationship names.
///
/// Names are compared case-insensitively. Duplicate table names, duplicate column names
/// within a table, and relationships naming missing tables/columns are rejected.
pub fn parse_formulas(&mut self) -> Result<(), ModelError> {
let mut tables: BTreeMap<String, usize> = BTreeMap::new();
for (index, table) in self.tables.iter().enumerate() {
let key = table.name.to_ascii_lowercase();
if tables.insert(key, index).is_some() {
return Err(ModelError::new(format!("duplicate model table `{}`", table.name)));
}
let mut columns = BTreeMap::new();
for column in &table.columns {
if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() {
return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name)));
}
}
}
for relationship in &self.relationships {
self.require_column(&relationship.from_table, &relationship.from_column)?;
self.require_column(&relationship.to_table, &relationship.to_column)?;
}
let mut names = BTreeMap::new();
for measure in &mut self.measures {
// Measure names are compared case-insensitively everywhere else, so a duplicate would
// silently hide the second formula.
if names.insert(measure.name.to_ascii_lowercase(), ()).is_some() {
return Err(ModelError::new(format!("duplicate measure `{}`", measure.name)));
}
let expr = parse_expression(&measure.formula).map_err(|error| ModelError::new(format!("measure `{}`: {error}", measure.name)))?;
measure.expr = Some(expr);
}
Ok(())
}
/// The index of a table, ignoring case.
pub fn table_index(&self, name: &str) -> Option<usize> {
self.tables.iter().position(|table| table.name.eq_ignore_ascii_case(name))
}
/// The index of a column within a table, ignoring case.
pub fn column_index(&self, table: usize, name: &str) -> Option<usize> {
self.tables.get(table)?.columns.iter().position(|column| column.name.eq_ignore_ascii_case(name))
}
/// The index of a measure, ignoring case.
pub fn measure_index(&self, name: &str) -> Option<usize> {
self.measures.iter().position(|measure| measure.name.eq_ignore_ascii_case(name))
}
/// Tables that contain a column with this name.
pub fn tables_with_column(&self, name: &str) -> Vec<usize> {
self.tables
.iter()
.enumerate()
.filter(|(_, table)| table.columns.iter().any(|column| column.name.eq_ignore_ascii_case(name)))
.map(|(index, _)| index)
.collect()
}
fn require_column(&self, table: &str, column: &str) -> Result<(), ModelError> {
let Some(table_index) = self.table_index(table) else {
return Err(ModelError::new(format!("relationship names missing table `{table}`")));
};
if self.column_index(table_index, column).is_none() {
return Err(ModelError::new(format!("relationship names missing column `{column}` in table `{table}`")));
}
Ok(())
}
}
/// The result of [`parse_expression`] for a measure, used by callers that want to surface the
/// parse error separately from the model metadata.
pub fn parse_measure(formula: &str) -> Result<Expr, ParseError> {
parse_expression(formula)
}
#[cfg(test)]
mod tests {
use super::*;
/// The model JSON `docs/power-pivot.md` documents, written before the metadata fields existed.
/// It must keep loading (the metadata parser ignores everything it does not own), and adding
/// the fields must not change what the document means.
const OLD_SCHEMA: &str = r#"{
"tables": [{"name":"Sales","columns":[{"name":"Region","data_type":"String"},{"name":"Amount","data_type":"Double"}],
"rows":[["East",10],["West",20]]}],
"relationships": [],
"measures": [{"name":"Total Sales","formula":"SUM(Sales[Amount])","table":"Sales"}]
}"#;
#[test]
fn old_schema_json_loads_with_default_metadata() {
let mut model: DataModel = serde_json::from_str(OLD_SCHEMA).expect("old model JSON loads");
model.parse_formulas().expect("old model JSON validates");
assert_eq!(model.tables[0].columns.len(), 2, "unknown metadata keys never disturb the model");
let metadata = ModelMetadata::from_model_json(OLD_SCHEMA).expect("old model JSON has valid metadata");
let table = metadata.table("sales").expect("the table is in the metadata");
assert_eq!(table.date_column, None);
assert!(!metadata.column("Sales", "amount").expect("column metadata").hidden);
assert_eq!(metadata.column("Sales", "Amount").and_then(|column| column.summarize_by.clone()), None);
let written = serde_json::to_value(&metadata).expect("metadata serializes");
assert!(written["tables"][0].get("date_column").is_none(), "an unmarked table writes no date column: {written}");
assert!(written["tables"][0]["columns"][0].get("hidden").is_none(), "a visible column writes no hidden flag: {written}");
assert!(written["tables"][0]["columns"][0].get("summarize_by").is_none(), "an absent summarization stays absent: {written}");
let reloaded = ModelMetadata::from_model_json(&written.to_string()).expect("the written metadata reloads");
assert_eq!(reloaded, metadata);
}
#[test]
fn new_metadata_is_read_from_the_model_document() {
let json = r#"{
"tables": [{"name":"Calendar","date_column":"date",
"columns":[{"name":"Date","data_type":"DateTime"},{"name":"Secret","hidden":true,"summarize_by":"do not summarize"}],
"rows":[[45292,null]]}],
"relationships": [],
"measures": []
}"#;
let mut model: DataModel = serde_json::from_str(json).expect("JSON with metadata loads");
model.parse_formulas().expect("the model validates");
let metadata = ModelMetadata::from_model_json(json).expect("the metadata validates");
let table = metadata.table("Calendar").expect("a table");
assert_eq!(table.date_column.as_deref(), Some("Date"), "the stored name takes the column's spelling");
let secret = metadata.column("calendar", "SECRET").expect("column metadata");
assert!(secret.hidden);
assert_eq!(secret.summarize_by.as_deref(), Some("None"), "the summarization is canonicalized");
}
#[test]
fn metadata_naming_missing_columns_or_aggregates_is_rejected() {
let bad_date = r#"{"tables":[{"name":"T","columns":[{"name":"A"}],"rows":[],"date_column":"Missing"}]}"#;
assert!(ModelMetadata::from_model_json(bad_date).is_err(), "a date column that is not a column is rejected");
let bad_summary = r#"{"tables":[{"name":"T","columns":[{"name":"A","summarize_by":"median"}],"rows":[]}]}"#;
assert!(ModelMetadata::from_model_json(bad_summary).is_err(), "an unknown summarization is rejected");
let duplicate = r#"{"tables":[{"name":"T","columns":[{"name":"A"},{"name":"a"}]}]}"#;
assert!(ModelMetadata::from_model_json(duplicate).is_err(), "ambiguous column names are rejected");
}
#[test]
fn summarize_by_names_match_loosely() {
assert_eq!(summarize_by_name("SUM"), Some("Sum"));
assert_eq!(summarize_by_name("average"), Some("Average"));
assert_eq!(summarize_by_name("Do Not Summarize"), Some("None"));
assert_eq!(summarize_by_name("median"), None);
}
}
-878
View File
@@ -1,878 +0,0 @@
//! Pratt parser: tokens → [`Expr`] / [`Query`].
//!
//! Binding powers encode the operator table (tighter binds first): parentheses and function
//! calls; `^`; unary `+`/`-`; `*`/`/`; binary `+`/`-`; `&`; comparisons, which include `IN`; `NOT`;
//! `&&`; `||`. Every operator is left-associative, including `^`: Microsoft's operator reference
//! orders equal-precedence operators from left to right, so `2^3^2` is `(2^3)^2`.
use crate::ast::{
Axis, AxisGroup, AxisKind, AxisOrderItem, BinaryOp, Call, ColumnDef, Define, Definition, Evaluate, Expr, ExprKind, FunctionDef, FunctionParam,
Literal, MParameterDef, MeasureDef, Name, NameRef, OrderItem, ParameterSubtype, ParameterType, PassingMode, Query, SortDirection, Span,
StartValue, TableDef, UnaryOp, VarDecl, VarDef, VisualShape,
};
use crate::lexer::{LexError, Token, TokenKind, tokenize};
/// Deepest expression nesting accepted. Bounds parser recursion (and the tree that later
/// evaluation walks) at 256 levels.
pub const MAX_DEPTH: usize = 256;
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("{message} at bytes {}..{}", span.start, span.end)]
pub struct ParseError {
pub message: String,
pub span: Span,
}
impl ParseError {
fn new(message: impl Into<String>, span: Span) -> Self {
ParseError { message: message.into(), span }
}
}
impl From<LexError> for ParseError {
fn from(e: LexError) -> Self {
ParseError { message: e.message, span: e.span }
}
}
/// Parses a DAX expression. A single leading `=` (as typed in some editors) is accepted and
/// ignored.
pub fn parse_expression(src: &str) -> Result<Expr, ParseError> {
if src.len() > crate::MAX_INPUT_LEN {
return Err(ParseError::new(
format!("input is too long ({} bytes, limit {})", src.len(), crate::MAX_INPUT_LEN),
crate::Span::new(0, src.len()),
));
}
let tokens = tokenize(src)?;
let mut parser = Parser { tokens, i: 0, depth: 0 };
if matches!(parser.peek(), TokenKind::Eq) {
parser.next();
}
let expr = parser.expr(0)?;
parser.expect_eof()?;
ensure_depth(&expr)?;
Ok(expr)
}
/// Parses a DAX query: an optional `DEFINE` block followed by one or more `EVALUATE` statements.
///
/// For the simple form `EVALUATE <expression>` the result has `define: None` and a single
/// evaluation with empty `order_by`/`start_at`. An optional trailing `;` is accepted; it is not
/// part of the grammar, only a recovery extension.
///
/// Statement keywords (`DEFINE`, `MEASURE`, `COLUMN`, `TABLE`, `VAR`, `RETURN`, `FUNCTION`,
/// `MPARAMETER`, `ORDER BY`, `START AT`, `WITH VISUAL SHAPE`, `AXIS`, `GROUP`, `TOTAL`,
/// `DENSIFY`, `ASC`, `DESC`) are recognised case-insensitively at the positions where they are
/// expected. Definition bounds and statement bounds therefore come from those keywords, never
/// from newlines.
pub fn parse_query(src: &str) -> Result<Query, ParseError> {
if src.len() > crate::MAX_QUERY_LEN {
return Err(ParseError::new(
format!("query is too long ({} bytes, limit {})", src.len(), crate::MAX_QUERY_LEN),
crate::Span::new(0, src.len()),
));
}
let tokens = tokenize(src)?;
let mut parser = Parser { tokens, i: 0, depth: 0 };
let query = parser.query()?;
validate_query_depth(&query)?;
Ok(query)
}
/// Rejects an AST deeper than [`MAX_DEPTH`] even when parser recursion stayed shallow (for
/// example a function call wrapped around a grouped chain).
fn ensure_depth(expr: &Expr) -> Result<(), ParseError> {
let depth = expr.depth();
if depth > MAX_DEPTH {
return Err(ParseError::new(format!("expression is nested too deeply (limit {MAX_DEPTH})"), expr.span));
}
Ok(())
}
/// Applies the AST-depth bound to every expression in a query, not only to the last parsed
/// `EVALUATE` expression.
fn validate_query_depth(query: &Query) -> Result<(), ParseError> {
if let Some(define) = &query.define {
for item in &define.items {
match item {
Definition::Measure(def) => ensure_depth(&def.expr)?,
Definition::Column(def) => ensure_depth(&def.expr)?,
Definition::Table(def) => ensure_depth(&def.expr)?,
Definition::Var(def) => ensure_depth(&def.expr)?,
Definition::MParameter(def) => ensure_depth(&def.expr)?,
Definition::Function(def) => {
ensure_depth(&def.body)?;
for param in &def.params {
if let Some(default) = &param.default {
ensure_depth(default)?;
}
}
}
}
}
}
for evaluate in &query.evaluates {
ensure_depth(&evaluate.table)?;
for item in &evaluate.order_by {
ensure_depth(&item.expr)?;
}
}
Ok(())
}
fn describe(kind: &TokenKind) -> String {
match kind {
TokenKind::Integer(n) => format!("integer literal `{n}`"),
TokenKind::Decimal(n) => format!("decimal literal `{n}`"),
TokenKind::DateTime(value) => format!("date/time literal `dt\"{value}\"`"),
TokenKind::String(_) => "string literal".into(),
TokenKind::Ident(s) => format!("`{s}`"),
TokenKind::QuotedIdent(_) => "quoted identifier".into(),
TokenKind::BracketIdent(_) => "bracketed identifier".into(),
TokenKind::Not => "`NOT`".into(),
TokenKind::In => "`IN`".into(),
TokenKind::Evaluate => "`EVALUATE`".into(),
TokenKind::Plus => "`+`".into(),
TokenKind::Minus => "`-`".into(),
TokenKind::Star => "`*`".into(),
TokenKind::Slash => "`/`".into(),
TokenKind::Caret => "`^`".into(),
TokenKind::Amp => "`&`".into(),
TokenKind::Eq => "`=`".into(),
TokenKind::StrictEq => "`==`".into(),
TokenKind::NotEq => "`<>`".into(),
TokenKind::Lt => "`<`".into(),
TokenKind::Gt => "`>`".into(),
TokenKind::Le => "`<=`".into(),
TokenKind::Ge => "`>=`".into(),
TokenKind::AndAnd => "`&&`".into(),
TokenKind::OrOr => "`||`".into(),
TokenKind::Arrow => "`=>`".into(),
TokenKind::Colon => "`:`".into(),
TokenKind::AtName(name) => format!("parameter `@{name}`"),
TokenKind::Semicolon => "`;`".into(),
TokenKind::LParen => "`(`".into(),
TokenKind::RParen => "`)`".into(),
TokenKind::LBrace => "`{`".into(),
TokenKind::RBrace => "`}`".into(),
TokenKind::Comma => "`,`".into(),
TokenKind::Eof => "end of input".into(),
}
}
struct Parser {
tokens: Vec<Token>,
i: usize,
depth: usize,
}
impl Parser {
fn peek(&self) -> &TokenKind {
self.tokens.get(self.i).map(|t| &t.kind).unwrap_or(&TokenKind::Eof)
}
fn peek_span(&self) -> Span {
self.tokens.get(self.i).map(|t| t.span).unwrap_or(Span::empty())
}
fn next(&mut self) -> Token {
let token = self.tokens.get(self.i).cloned().unwrap_or(Token { kind: TokenKind::Eof, span: Span::empty() });
if self.i < self.tokens.len() {
self.i += 1;
}
token
}
fn error_here(&self, message: impl Into<String>) -> ParseError {
ParseError::new(message, self.peek_span())
}
fn expect(&mut self, kind: TokenKind, context: &str) -> Result<Token, ParseError> {
if *self.peek() == kind {
Ok(self.next())
} else {
Err(self.error_here(format!("expected {}, found {}; {context}", describe(&kind), describe(self.peek()))))
}
}
fn expect_eof(&self) -> Result<(), ParseError> {
match self.peek() {
TokenKind::Eof => Ok(()),
other => Err(self.error_here(format!("unexpected {} after expression", describe(other)))),
}
}
fn expect_query_eof(&self) -> Result<(), ParseError> {
match self.peek() {
TokenKind::Eof => Ok(()),
other => Err(self.error_here(format!("unexpected {} after the query", describe(other)))),
}
}
/// The current token when it is a bare identifier, which is how statement keywords are
/// lexed. Keywords are matched case-insensitively by their text.
fn peek_word(&self) -> Option<&str> {
match self.peek() {
TokenKind::Ident(word) => Some(word),
_ => None,
}
}
fn keyword_at(&self, word: &str) -> bool {
self.peek_word().is_some_and(|text| text.eq_ignore_ascii_case(word))
}
fn expect_keyword(&mut self, word: &str, context: &str) -> Result<Token, ParseError> {
if self.keyword_at(word) {
Ok(self.next())
} else {
Err(self.error_here(format!("expected `{word}`, found {}; {context}", describe(self.peek()))))
}
}
// -------------------------------------------------------------------------------------
// Query statements
// -------------------------------------------------------------------------------------
fn query(&mut self) -> Result<Query, ParseError> {
let define = if self.keyword_at("DEFINE") { Some(self.define_block()?) } else { None };
if !matches!(self.peek(), TokenKind::Evaluate) {
return Err(self.error_here("a query needs at least one `EVALUATE` statement"));
}
let mut evaluates = Vec::new();
while matches!(self.peek(), TokenKind::Evaluate) {
evaluates.push(self.evaluate_statement()?);
}
// The documented grammar has no statement terminators. A trailing `;` is accepted as a
// recovery extension only, never required.
while matches!(self.peek(), TokenKind::Semicolon) {
self.next();
}
self.expect_query_eof()?;
Ok(Query { define, evaluates })
}
fn define_block(&mut self) -> Result<Define, ParseError> {
let keyword = self.next();
let mut items = Vec::new();
loop {
let Some(word) = self.peek_word().map(str::to_owned) else {
match self.peek() {
TokenKind::Evaluate | TokenKind::Eof | TokenKind::Semicolon => break,
other => {
return Err(self.error_here(format!(
"expected a DEFINE entry (MEASURE, COLUMN, TABLE, VAR, FUNCTION or MPARAMETER), found {}",
describe(other)
)));
}
}
};
if word.eq_ignore_ascii_case("MEASURE") {
self.next();
items.push(Definition::Measure(self.measure_definition()?));
} else if word.eq_ignore_ascii_case("COLUMN") {
self.next();
items.push(Definition::Column(self.column_definition()?));
} else if word.eq_ignore_ascii_case("TABLE") {
self.next();
items.push(Definition::Table(self.table_definition()?));
} else if word.eq_ignore_ascii_case("VAR") {
self.next();
items.push(Definition::Var(self.var_definition()?));
} else if word.eq_ignore_ascii_case("FUNCTION") {
self.next();
items.push(Definition::Function(self.function_definition()?));
} else if word.eq_ignore_ascii_case("MPARAMETER") {
self.next();
items.push(Definition::MParameter(self.mparameter_definition()?));
} else {
return Err(self.error_here(format!("expected a DEFINE entry (MEASURE, COLUMN, TABLE, VAR, FUNCTION or MPARAMETER), found `{word}`")));
}
}
if items.is_empty() {
return Err(ParseError::new("DEFINE needs at least one definition before `EVALUATE`", keyword.span));
}
Ok(Define { items })
}
fn measure_definition(&mut self) -> Result<MeasureDef, ParseError> {
let name = self.definition_name("measure")?;
self.expect(TokenKind::Eq, "a MEASURE definition needs `=` before its expression")?;
let expr = self.expr(0)?;
Ok(MeasureDef { name, expr })
}
fn column_definition(&mut self) -> Result<ColumnDef, ParseError> {
let name = self.definition_name("column")?;
self.expect(TokenKind::Eq, "a COLUMN definition needs `=` before its expression")?;
let expr = self.expr(0)?;
Ok(ColumnDef { name, expr })
}
fn var_definition(&mut self) -> Result<VarDef, ParseError> {
let name = self.variable_name()?;
self.expect(TokenKind::Eq, "a query-scoped VAR needs `=` before its expression")?;
let expr = self.expr(0)?;
Ok(VarDef { name, expr })
}
fn table_definition(&mut self) -> Result<TableDef, ParseError> {
let name = self.table_name("table")?;
self.expect(TokenKind::Eq, "a TABLE definition needs `=` before its table expression")?;
let expr = self.expr(0)?;
let visual_shape = if self.keyword_at("WITH") { Some(self.visual_shape()?) } else { None };
Ok(TableDef { name, expr, visual_shape })
}
fn mparameter_definition(&mut self) -> Result<MParameterDef, ParseError> {
let name = self.table_name("M parameter")?;
self.expect(TokenKind::Eq, "an MPARAMETER definition needs `=` before its expression")?;
let expr = self.expr(0)?;
Ok(MParameterDef { name, expr })
}
fn function_definition(&mut self) -> Result<FunctionDef, ParseError> {
let name = self.table_name("function")?;
self.expect(TokenKind::Eq, "a FUNCTION definition needs `=` before its parameter list")?;
self.expect(TokenKind::LParen, "a FUNCTION definition needs a parenthesised parameter list")?;
let mut params = Vec::new();
if matches!(self.peek(), TokenKind::RParen) {
self.next();
} else {
loop {
params.push(self.function_param()?);
let token = self.next();
match token.kind {
TokenKind::Comma => {
if matches!(self.peek(), TokenKind::RParen) {
return Err(self.error_here("expected a parameter after `,`"));
}
}
TokenKind::RParen => break,
other => {
return Err(ParseError::new(format!("expected `,` or `)` in the parameter list, found {}", describe(&other)), token.span));
}
}
}
}
self.expect(TokenKind::Arrow, "a FUNCTION definition needs `=>` before its body")?;
let body = self.expr(0)?;
Ok(FunctionDef { name, params, body })
}
fn function_param(&mut self) -> Result<FunctionParam, ParseError> {
let token = self.next();
let name = match &token.kind {
TokenKind::Ident(text) => Name::bare(text.clone()),
other => return Err(ParseError::new(format!("expected a parameter name, found {}", describe(other)), token.span)),
};
let mut ty = None;
let mut subtype = None;
let mut passing = None;
if matches!(self.peek(), TokenKind::Colon) {
let colon = self.next();
let mut annotated = false;
while let Some(word) = self.peek_word().map(str::to_owned) {
if let Some(parsed) = ParameterType::from_keyword(&word) {
if ty.is_some() {
return Err(self.error_here(format!("duplicate parameter type `{}`", parsed.keyword())));
}
if subtype.is_some() || passing.is_some() {
return Err(self.error_here("the parameter type must come before its subtype and passing mode"));
}
ty = Some(parsed);
} else if let Some(parsed) = ParameterSubtype::from_keyword(&word) {
if subtype.is_some() {
return Err(self.error_here(format!("duplicate parameter subtype `{}`", parsed.keyword())));
}
if passing.is_some() {
return Err(self.error_here("the parameter subtype must come before its passing mode"));
}
subtype = Some(parsed);
} else if let Some(parsed) = PassingMode::from_keyword(&word) {
if passing.is_some() {
return Err(self.error_here("duplicate parameter passing mode"));
}
passing = Some(parsed);
} else {
return Err(self.error_here(format!("unknown function parameter type `{word}`")));
}
self.next();
annotated = true;
}
if !annotated {
return Err(ParseError::new("expected a parameter type, subtype or passing mode after `:`", colon.span));
}
if subtype.is_some() && ty.is_some_and(|ty| ty != ParameterType::Scalar) {
return Err(self.error_here("only SCALAR parameters accept a subtype"));
}
}
let default = if matches!(self.peek(), TokenKind::Eq) {
self.next();
Some(self.expr(0)?)
} else {
None
};
Ok(FunctionParam { name, ty, subtype, passing, default })
}
fn evaluate_statement(&mut self) -> Result<Evaluate, ParseError> {
self.next(); // EVALUATE
let table = self.expr(0)?;
let order_by = if self.keyword_at("ORDER") {
self.next();
self.expect_keyword("BY", "ORDER must be followed by BY")?;
self.order_items()?
} else {
Vec::new()
};
let start_at = if self.keyword_at("START") {
let span = self.peek_span();
self.next();
self.expect_keyword("AT", "START must be followed by AT")?;
if order_by.is_empty() {
return Err(ParseError::new("START AT requires a preceding ORDER BY clause", span));
}
let values = self.start_values()?;
if values.len() > order_by.len() {
return Err(ParseError::new(format!("START AT has {} value(s) but ORDER BY has {} item(s)", values.len(), order_by.len()), span));
}
values
} else {
Vec::new()
};
Ok(Evaluate { table, order_by, start_at })
}
fn order_items(&mut self) -> Result<Vec<OrderItem>, ParseError> {
let mut items = Vec::new();
loop {
let expr = self.expr(0)?;
let direction = self.direction();
items.push(OrderItem { expr, direction });
if matches!(self.peek(), TokenKind::Comma) {
self.next();
} else {
break;
}
}
Ok(items)
}
fn direction(&mut self) -> SortDirection {
if self.keyword_at("ASC") {
self.next();
SortDirection::Asc
} else if self.keyword_at("DESC") {
self.next();
SortDirection::Desc
} else {
SortDirection::Asc
}
}
fn start_values(&mut self) -> Result<Vec<StartValue>, ParseError> {
let mut values = Vec::new();
loop {
values.push(self.start_value()?);
if matches!(self.peek(), TokenKind::Comma) {
self.next();
} else {
break;
}
}
Ok(values)
}
fn start_value(&mut self) -> Result<StartValue, ParseError> {
let token = self.next();
let negative = match &token.kind {
TokenKind::Minus => Some(true),
TokenKind::Plus => Some(false),
_ => None,
};
if let Some(negative) = negative {
let literal = self.next();
return match literal.kind {
TokenKind::Integer(value) => Ok(StartValue::Literal(Literal::Integer(if negative { -value } else { value }))),
TokenKind::Decimal(value) => Ok(StartValue::Literal(Literal::Decimal(if negative { -value } else { value }))),
other => Err(ParseError::new(format!("a signed START AT value must be a numeric literal, found {}", describe(&other)), literal.span)),
};
}
match token.kind {
TokenKind::Integer(value) => Ok(StartValue::Literal(Literal::Integer(value))),
TokenKind::Decimal(value) => Ok(StartValue::Literal(Literal::Decimal(value))),
TokenKind::DateTime(value) => Ok(StartValue::Literal(Literal::DateTime(value))),
TokenKind::String(value) => Ok(StartValue::Literal(Literal::String(value))),
TokenKind::AtName(name) => Ok(StartValue::Parameter(Name::bare(name))),
TokenKind::Ident(word) if word.eq_ignore_ascii_case("TRUE") => Ok(StartValue::Literal(Literal::Boolean(true))),
TokenKind::Ident(word) if word.eq_ignore_ascii_case("FALSE") => Ok(StartValue::Literal(Literal::Boolean(false))),
other => Err(ParseError::new(format!("expected a literal or @parameter in START AT, found {}", describe(&other)), token.span)),
}
}
fn visual_shape(&mut self) -> Result<VisualShape, ParseError> {
self.next(); // WITH
self.expect_keyword("VISUAL", "WITH must be followed by VISUAL SHAPE")?;
self.expect_keyword("SHAPE", "WITH VISUAL SHAPE is a single clause")?;
let mut axes = Vec::new();
while self.keyword_at("AXIS") {
let span = self.peek_span();
let axis = self.axis()?;
if axes.iter().any(|existing: &Axis| existing.kind == axis.kind) {
return Err(ParseError::new(format!("duplicate AXIS {} clause", axis.kind.keyword()), span));
}
axes.push(axis);
}
if axes.is_empty() {
return Err(self.error_here("WITH VISUAL SHAPE needs at least one AXIS ROWS or AXIS COLUMNS clause"));
}
let densify = if self.keyword_at("DENSIFY") {
self.next();
let value = self.next();
match value.kind {
TokenKind::String(text) => Some(text),
other => {
return Err(ParseError::new(format!("DENSIFY needs a double-quoted column name, found {}", describe(&other)), value.span));
}
}
} else {
None
};
Ok(VisualShape { axes, densify })
}
fn axis(&mut self) -> Result<Axis, ParseError> {
self.next(); // AXIS
let kind_token = self.next();
let kind = match &kind_token.kind {
TokenKind::Ident(word) if word.eq_ignore_ascii_case("ROWS") => AxisKind::Rows,
TokenKind::Ident(word) if word.eq_ignore_ascii_case("COLUMNS") => AxisKind::Columns,
other => {
return Err(ParseError::new(format!("expected `ROWS` or `COLUMNS` after AXIS, found {}", describe(other)), kind_token.span));
}
};
let mut groups = Vec::new();
while self.keyword_at("GROUP") {
self.next();
let mut columns = vec![self.column_ref("GROUP")?];
while matches!(self.peek(), TokenKind::Comma) {
self.next();
columns.push(self.column_ref("GROUP")?);
}
self.expect_keyword("TOTAL", "each GROUP needs a TOTAL column")?;
let total = self.column_ref("TOTAL")?;
groups.push(AxisGroup { columns, total });
}
if groups.is_empty() {
return Err(self.error_here("AXIS needs at least one GROUP ... TOTAL level"));
}
self.expect_keyword("ORDER", "each AXIS needs an ORDER BY clause")?;
self.expect_keyword("BY", "each AXIS needs an ORDER BY clause")?;
let mut order_by = Vec::new();
loop {
let column = self.column_ref("ORDER BY")?;
let direction = self.direction();
order_by.push(AxisOrderItem { column, direction });
if matches!(self.peek(), TokenKind::Comma) {
self.next();
} else {
break;
}
}
Ok(Axis { kind, groups, order_by })
}
/// A table name in a definition: a bare identifier or a single-quoted name.
fn table_name(&mut self, what: &str) -> Result<Name, ParseError> {
let token = self.next();
match &token.kind {
TokenKind::Ident(text) => Ok(Name::bare(text.clone())),
TokenKind::QuotedIdent(text) => Ok(Name::quoted(text.clone())),
other => Err(ParseError::new(format!("expected a {what} name, found {}", describe(other)), token.span)),
}
}
/// `<table>[<name>]`, the name of a MEASURE or COLUMN definition.
fn definition_name(&mut self, kind: &str) -> Result<NameRef, ParseError> {
let table = self.table_name(kind)?;
let token = self.next();
match &token.kind {
TokenKind::BracketIdent(text) => Ok(NameRef::qualified(table, Name::bracketed(text.clone()))),
other => Err(ParseError::new(format!("expected a bracketed {kind} name after the table name, found {}", describe(other)), token.span)),
}
}
/// A variable name: a plain identifier, never quoted or bracketed.
fn variable_name(&mut self) -> Result<Name, ParseError> {
let token = self.next();
match &token.kind {
TokenKind::Ident(text) => Ok(Name::bare(text.clone())),
TokenKind::QuotedIdent(_) | TokenKind::BracketIdent(_) => {
Err(ParseError::new("variable names cannot be quoted or bracketed", token.span))
}
other => Err(ParseError::new(format!("expected a variable name, found {}", describe(other)), token.span)),
}
}
/// A column reference: `[Column]`, `Table[Column]` or `'Table'[Column]`.
fn column_ref(&mut self, context: &str) -> Result<NameRef, ParseError> {
let token = self.next();
let table = match &token.kind {
TokenKind::BracketIdent(text) => return Ok(NameRef::unqualified(Name::bracketed(text.clone()))),
TokenKind::Ident(text) => Name::bare(text.clone()),
TokenKind::QuotedIdent(text) => Name::quoted(text.clone()),
other => {
return Err(ParseError::new(format!("expected a column reference in {context}, found {}", describe(other)), token.span));
}
};
let column = self.next();
match &column.kind {
TokenKind::BracketIdent(text) => Ok(NameRef::qualified(table, Name::bracketed(text.clone()))),
other => Err(ParseError::new(format!("expected a bracketed column name after the table name, found {}", describe(other)), column.span)),
}
}
fn enter(&mut self) -> Result<(), ParseError> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return Err(self.error_here(format!("expression is nested too deeply (limit {MAX_DEPTH})")));
}
Ok(())
}
fn leave(&mut self) {
self.depth = self.depth.saturating_sub(1);
}
fn binary_op(&self) -> Option<BinaryOp> {
match self.peek() {
TokenKind::Plus => Some(BinaryOp::Add),
TokenKind::Minus => Some(BinaryOp::Sub),
TokenKind::Star => Some(BinaryOp::Mul),
TokenKind::Slash => Some(BinaryOp::Div),
TokenKind::Caret => Some(BinaryOp::Pow),
TokenKind::Amp => Some(BinaryOp::Concat),
TokenKind::Eq => Some(BinaryOp::Eq),
TokenKind::StrictEq => Some(BinaryOp::StrictEq),
TokenKind::NotEq => Some(BinaryOp::Ne),
TokenKind::Lt => Some(BinaryOp::Lt),
TokenKind::Gt => Some(BinaryOp::Gt),
TokenKind::Le => Some(BinaryOp::Le),
TokenKind::Ge => Some(BinaryOp::Ge),
TokenKind::AndAnd => Some(BinaryOp::And),
TokenKind::OrOr => Some(BinaryOp::Or),
TokenKind::In => Some(BinaryOp::In),
_ => None,
}
}
fn expr(&mut self, min_bp: u8) -> Result<Expr, ParseError> {
self.enter()?;
let mut lhs = self.prefix()?;
let mut lhs_depth = lhs.depth();
while let Some(op) = self.binary_op() {
let bp = op.precedence();
if bp < min_bp {
break;
}
self.next();
// Every binary operator is left-associative (DAX orders equal precedence left to right).
let next_min = if op.is_right_associative() { bp } else { bp + 1 };
let rhs = self.expr(next_min)?;
// Grouped expressions return their inner tree without a parenthesis node, so the
// depth must come from the AST itself, not from the parser's recursion frames.
let depth = lhs_depth.max(rhs.depth());
if depth >= MAX_DEPTH {
return Err(self.error_here(format!("expression is nested too deeply (limit {MAX_DEPTH})")));
}
lhs_depth = depth + 1;
let span = lhs.span.to(rhs.span);
lhs = Expr::new(ExprKind::Binary { op, left: Box::new(lhs), right: Box::new(rhs) }, span);
}
self.leave();
Ok(lhs)
}
fn prefix(&mut self) -> Result<Expr, ParseError> {
let token = self.next();
match token.kind {
TokenKind::Integer(n) => Ok(Expr::literal(Literal::Integer(n), token.span)),
TokenKind::Decimal(n) => Ok(Expr::literal(Literal::Decimal(n), token.span)),
TokenKind::DateTime(value) => Ok(Expr::literal(Literal::DateTime(value), token.span)),
TokenKind::String(s) => Ok(Expr::literal(Literal::String(s), token.span)),
TokenKind::Ident(word) => {
if word.eq_ignore_ascii_case("VAR") {
return self.var_return(token.span);
}
if word.eq_ignore_ascii_case("RETURN") {
return Err(ParseError::new("RETURN without a preceding VAR declaration", token.span));
}
self.prefix_ident(word, token.span)
}
TokenKind::QuotedIdent(word) => {
let name = Name::quoted(word);
if let TokenKind::BracketIdent(_) = self.peek() {
self.qualified_name(name, token.span)
} else {
Ok(Expr::new(ExprKind::Name(NameRef::unqualified(name)), token.span))
}
}
TokenKind::BracketIdent(word) => Ok(Expr::new(ExprKind::Name(NameRef::unqualified(Name::bracketed(word))), token.span)),
TokenKind::Not => {
let operand = self.expr(UnaryOp::Not.precedence())?;
let span = token.span.to(operand.span);
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Not, expr: Box::new(operand) }, span))
}
TokenKind::Plus => {
let operand = self.expr(UnaryOp::Plus.precedence())?;
let span = token.span.to(operand.span);
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Plus, expr: Box::new(operand) }, span))
}
TokenKind::Minus => {
let operand = self.expr(UnaryOp::Neg.precedence())?;
let span = token.span.to(operand.span);
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Neg, expr: Box::new(operand) }, span))
}
TokenKind::LParen => self.paren(token.span),
TokenKind::LBrace => self.table(token.span),
_ => Err(ParseError::new(format!("expected expression, found {}", describe(&token.kind)), token.span)),
}
}
fn prefix_ident(&mut self, word: String, span: Span) -> Result<Expr, ParseError> {
if let TokenKind::BracketIdent(_) = self.peek() {
return self.qualified_name(Name::bare(word), span);
}
if matches!(self.peek(), TokenKind::LParen) {
return self.call(Name::bare(word), span);
}
if word.eq_ignore_ascii_case("TRUE") {
return Ok(Expr::literal(Literal::Boolean(true), span));
}
if word.eq_ignore_ascii_case("FALSE") {
return Ok(Expr::literal(Literal::Boolean(false), span));
}
Ok(Expr::new(ExprKind::Name(NameRef::unqualified(Name::bare(word))), span))
}
/// Parses `VAR <name> = <expr> ... RETURN <expr>`.
///
/// The declaration values and the `RETURN` body stop at the next statement or definition
/// keyword because a bare identifier is never an infix operator, so no newline or terminator
/// is needed. A nested `VAR ... RETURN ...` as a declaration value or body parses recursively.
fn var_return(&mut self, start: Span) -> Result<Expr, ParseError> {
let mut vars = Vec::new();
// The leading `VAR` has already been consumed by `prefix`; each iteration parses one
// declaration and continues only when another `VAR` follows the value expression.
loop {
let name = self.variable_name()?;
self.expect(TokenKind::Eq, "a VAR declaration needs `=` before its expression")?;
let expr = self.expr(0)?;
vars.push(VarDecl { name, expr });
if !self.keyword_at("VAR") {
break;
}
self.next();
}
if !self.keyword_at("RETURN") {
return Err(self.error_here("VAR declarations must be followed by RETURN <expression>"));
}
self.next();
let body = self.expr(0)?;
let span = start.to(body.span);
Ok(Expr::new(ExprKind::VarReturn { vars, body: Box::new(body) }, span))
}
/// Consumes a bracketed column that follows a table name.
fn qualified_name(&mut self, table: Name, table_span: Span) -> Result<Expr, ParseError> {
let column = self.next();
let TokenKind::BracketIdent(text) = column.kind else {
return Err(ParseError::new("expected bracketed column name", column.span));
};
let span = table_span.to(column.span);
Ok(Expr::new(ExprKind::Name(NameRef::qualified(table, Name::bracketed(text))), span))
}
fn call(&mut self, name: Name, name_span: Span) -> Result<Expr, ParseError> {
self.expect(TokenKind::LParen, "function calls need `(` after the name")?;
let mut args = Vec::new();
if matches!(self.peek(), TokenKind::RParen) {
let close = self.next();
return Ok(Expr::new(ExprKind::Call(Call { name, args }), name_span.to(close.span)));
}
let close_span = loop {
if matches!(self.peek(), TokenKind::RParen) {
return Err(self.error_here("expected an argument after `,`"));
}
args.push(self.expr(0)?);
let token = self.next();
match token.kind {
TokenKind::Comma => {}
TokenKind::RParen => break token.span,
_ => {
return Err(ParseError::new(
format!("expected `,` or `)` in call to `{}`, found {}", name.text, describe(&token.kind)),
token.span,
));
}
}
};
Ok(Expr::new(ExprKind::Call(Call { name, args }), name_span.to(close_span)))
}
/// `( expr )` is grouping (parentheses are not AST nodes), `( a, b, ... )` is a row
/// constructor.
fn paren(&mut self, open: Span) -> Result<Expr, ParseError> {
if matches!(self.peek(), TokenKind::RParen) {
let close = self.next();
return Err(ParseError::new("empty parentheses are not an expression", open.to(close.span)));
}
let first = self.expr(0)?;
if matches!(self.peek(), TokenKind::Comma) {
let mut items = vec![first];
while matches!(self.peek(), TokenKind::Comma) {
self.next();
if matches!(self.peek(), TokenKind::RParen | TokenKind::Eof) {
return Err(self.error_here("expected an expression after `,` in a row constructor"));
}
items.push(self.expr(0)?);
}
let close = self.expect(TokenKind::RParen, "row constructors end with `)`")?;
return Ok(Expr::new(ExprKind::Tuple(items), open.to(close.span)));
}
let close = self.expect(TokenKind::RParen, "parentheses end with `)`")?;
Ok(Expr::new(first.kind, open.to(close.span)))
}
fn table(&mut self, open: Span) -> Result<Expr, ParseError> {
let mut items = Vec::new();
if matches!(self.peek(), TokenKind::RBrace) {
let close = self.next();
return Ok(Expr::new(ExprKind::Table(items), open.to(close.span)));
}
loop {
if matches!(self.peek(), TokenKind::RBrace | TokenKind::Eof) {
return Err(self.error_here("expected a value in the table constructor"));
}
items.push(self.expr(0)?);
match self.next().kind {
TokenKind::Comma => {
if matches!(self.peek(), TokenKind::RBrace) {
return Err(self.error_here("expected a value after `,` in the table constructor"));
}
}
TokenKind::RBrace => break,
_ => {
return Err(ParseError::new(
"expected `,` or `}` in the table constructor",
self.tokens.get(self.i.saturating_sub(1)).map(|t| t.span).unwrap_or(open),
));
}
}
}
let close_span = self.tokens.get(self.i.saturating_sub(1)).map(|t| t.span).unwrap_or(open);
Ok(Expr::new(ExprKind::Table(items), open.to(close_span)))
}
}
-133
View File
@@ -1,133 +0,0 @@
//! Minimal pivot grouping over the in-memory model.
//!
//! A pivot groups a table by one or more column references and evaluates a measure once per
//! group. This is the integration point a workbook/PivotTable adapter can call; the full
//! PivotTable layout engine remains outside this crate.
use std::collections::BTreeMap;
use crate::binder::{BindError, Binder, BoundExpr};
use crate::eval::{Evaluator, FilterContext};
use crate::model::DataModel;
use crate::pivot_table::DEFAULT_MAX_CELLS;
use crate::value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue};
use crate::{Expr, parse_expression};
/// One grouping field.
#[derive(Clone, Debug)]
pub struct PivotField {
pub table: usize,
pub column: usize,
pub name: String,
}
/// Evaluates a measure grouped by the supplied row fields (no column fields).
pub fn pivot(model: &DataModel, measure: &str, row_fields: &[PivotField]) -> Result<TableValue, PivotError> {
pivot_cross(model, measure, row_fields, &[])
}
/// Evaluates a measure grouped by row fields and optional column fields.
///
/// The result has one column per row field followed by one measure column per distinct column
/// group. With no column fields the result is the usual grouped table. Group order is ascending;
/// BLANK is a group of its own. Missing combinations are BLANK.
pub fn pivot_cross(model: &DataModel, measure: &str, row_fields: &[PivotField], column_fields: &[PivotField]) -> Result<TableValue, PivotError> {
let evaluator = Evaluator::new(model)?;
let table_index = model
.measure_index(measure)
.and_then(|index| model.measures.get(index))
.and_then(|measure| measure.table.as_deref())
.and_then(|table| model.table_index(table));
let Some(table_index) = table_index else {
return Err(PivotError::Eval(EvalError::new(format!(
"measure `{measure}` has no home table; give the measure a home table, or set `PivotTable::source_table` and render through `PivotTable` instead of `pivot`/`pivot_cross`"
))));
};
let source = model.tables.get(table_index).ok_or_else(|| PivotError::Eval(EvalError::new("missing table")))?;
let mut row_groups: BTreeMap<Vec<ScalarKey>, Vec<Scalar>> = BTreeMap::new();
let mut column_groups: BTreeMap<Vec<ScalarKey>, Vec<Scalar>> = BTreeMap::new();
for row in &source.rows {
let row_values = group_values(row, row_fields, table_index)?;
row_groups.entry(row_values.iter().map(crate::value::distinct_key).collect()).or_insert(row_values);
if !column_fields.is_empty() {
let column_values = group_values(row, column_fields, table_index)?;
column_groups.entry(column_values.iter().map(crate::value::distinct_key).collect()).or_insert(column_values);
}
}
if column_fields.is_empty() {
column_groups.insert(Vec::new(), Vec::new());
}
if row_groups.len().checked_mul(column_groups.len()).is_none_or(|cells| cells > DEFAULT_MAX_CELLS) {
return Err(PivotError::Eval(EvalError::new(format!(
"pivot would materialize {} rows x {} columns, over the limit of {} cells",
row_groups.len(),
column_groups.len(),
DEFAULT_MAX_CELLS
))));
}
let mut columns = row_fields.iter().map(|field| TableColumn { name: field.name.clone() }).collect::<Vec<_>>();
let column_headers: Vec<(Vec<ScalarKey>, Vec<Scalar>)> = column_groups.into_iter().collect();
if column_fields.is_empty() {
columns.push(TableColumn { name: measure.to_string() });
} else {
for (_, values) in &column_headers {
// Headers show calendar text for dates and whole numbers without `.0`, as Excel does.
columns.push(TableColumn { name: values.iter().map(|value| value.to_dax_text()).collect::<Vec<_>>().join(" | ") });
}
}
let mut rows = Vec::with_capacity(row_groups.len());
for (row_key, row_values) in row_groups {
let mut out = row_values;
for (column_key, _) in &column_headers {
let mut filters = FilterContext::default();
for (field, key) in row_fields.iter().zip(&row_key) {
crate::pivot_table::narrow_to_key(&mut filters, field.table, field.column, key);
}
for (field, key) in column_fields.iter().zip(column_key) {
crate::pivot_table::narrow_to_key(&mut filters, field.table, field.column, key);
}
out.push(evaluator.evaluate_measure(measure, filters)?);
}
rows.push(out);
}
Ok(TableValue::new(columns, rows))
}
fn group_values(row: &[Scalar], fields: &[PivotField], table_index: usize) -> Result<Vec<Scalar>, PivotError> {
let mut values = Vec::with_capacity(fields.len());
for field in fields {
if field.table != table_index {
return Err(PivotError::Eval(EvalError::new("pivot fields must belong to the measure table")));
}
values.push(row.get(field.column).cloned().unwrap_or(Scalar::Blank));
}
Ok(values)
}
/// Parses field references such as `Sales[Region]` against the model.
pub fn pivot_fields(model: &DataModel, fields: &[String]) -> Result<Vec<PivotField>, PivotError> {
let binder = Binder::new(model);
let mut out = Vec::with_capacity(fields.len());
for field in fields {
let expr: Expr = parse_expression(field).map_err(|error| PivotError::Bind(BindError { message: error.message, span: error.span }))?;
let bound = binder.bind_expression(&expr)?;
let BoundExpr::Column { table, column } = bound else {
return Err(PivotError::Bind(BindError { message: format!("pivot field `{field}` is not a column reference"), span: expr.span }));
};
let name =
model.tables.get(table).and_then(|table| table.columns.get(column)).map(|column| column.name.clone()).unwrap_or_else(|| field.clone());
out.push(PivotField { table, column, name });
}
Ok(out)
}
#[derive(Debug, thiserror::Error)]
pub enum PivotError {
#[error(transparent)]
Bind(#[from] BindError),
#[error(transparent)]
Eval(#[from] EvalError),
}
File diff suppressed because it is too large Load Diff
-339
View File
@@ -1,339 +0,0 @@
//! Canonical DAX printer: [`Expr`] / [`Query`] → text.
//!
//! Printing is iterative (an explicit work stack), so long operator chains — which parse into
//! deep trees — cannot overflow the stack. Parentheses are emitted only where precedence or
//! associativity requires them; re-parsing the result yields the same AST (spans ignored).
use std::fmt::Write as _;
use crate::ast::{
Axis, Call, Definition, Evaluate, Expr, ExprKind, FunctionParam, Literal, Name, NameRef, NameStyle, Query, StartValue, UnaryOp, VisualShape,
};
/// An expression-level `VAR ... RETURN ...` binds looser than every operator, so it needs
/// parentheses whenever it is an operand rather than a whole expression.
const VAR_RETURN_BP: u8 = 1;
/// Prints an expression in canonical form.
pub fn print_expression(expr: &Expr) -> String {
let mut out = String::new();
write_expr(&mut out, expr, 0);
out
}
/// Prints a query in canonical form.
///
/// `DEFINE` entries are indented one level; `EVALUATE` is printed on one line for the simple
/// `EVALUATE <expression>` form and followed by indented `ORDER BY`/`START AT` clauses when they
/// exist. A visual shape prints its axes, groups, axis order and `DENSIFY` indented under the
/// `TABLE` definition. Re-parsing the result yields the same [`Query`] (spans ignored).
pub fn print_query(query: &Query) -> String {
let mut lines: Vec<String> = Vec::new();
if let Some(define) = &query.define {
lines.push("DEFINE".into());
for item in &define.items {
push_definition(&mut lines, item);
}
}
for evaluate in &query.evaluates {
push_evaluate(&mut lines, evaluate);
}
lines.join("\n")
}
fn print_name(name: &Name) -> String {
let mut out = String::new();
write_name(&mut out, name);
out
}
fn print_name_ref(name: &NameRef) -> String {
let mut out = String::new();
write_name_ref(&mut out, name);
out
}
fn push_definition(lines: &mut Vec<String>, definition: &Definition) {
match definition {
Definition::Measure(def) => lines.push(format!(" MEASURE {} = {}", print_name_ref(&def.name), print_expression(&def.expr))),
Definition::Column(def) => lines.push(format!(" COLUMN {} = {}", print_name_ref(&def.name), print_expression(&def.expr))),
Definition::Var(def) => lines.push(format!(" VAR {} = {}", print_name(&def.name), print_expression(&def.expr))),
Definition::MParameter(def) => {
lines.push(format!(" MPARAMETER {} = {}", print_name(&def.name), print_expression(&def.expr)));
}
Definition::Function(def) => {
let params: Vec<String> = def.params.iter().map(print_function_param).collect();
lines.push(format!(" FUNCTION {} = ({}) => {}", print_name(&def.name), params.join(", "), print_expression(&def.body)));
}
Definition::Table(def) => {
let mut head = format!(" TABLE {} = {}", print_name(&def.name), print_expression(&def.expr));
match &def.visual_shape {
None => lines.push(head),
Some(shape) => {
head.push_str(" WITH VISUAL SHAPE");
lines.push(head);
push_visual_shape(lines, shape);
}
}
}
}
}
fn print_function_param(param: &FunctionParam) -> String {
let mut out = print_name(&param.name);
let mut annotations: Vec<&'static str> = Vec::new();
if let Some(ty) = param.ty {
annotations.push(ty.keyword());
}
if let Some(subtype) = param.subtype {
annotations.push(subtype.keyword());
}
if let Some(passing) = param.passing {
annotations.push(passing.keyword());
}
if !annotations.is_empty() {
out.push_str(" : ");
out.push_str(&annotations.join(" "));
}
if let Some(default) = &param.default {
out.push_str(" = ");
out.push_str(&print_expression(default));
}
out
}
fn push_visual_shape(lines: &mut Vec<String>, shape: &VisualShape) {
for axis in &shape.axes {
push_axis(lines, axis);
}
if let Some(densify) = &shape.densify {
let mut line = String::from(" DENSIFY ");
write_quoted(&mut line, densify, '"');
lines.push(line);
}
}
fn push_axis(lines: &mut Vec<String>, axis: &Axis) {
lines.push(format!(" AXIS {}", axis.kind.keyword()));
for group in &axis.groups {
let columns: Vec<String> = group.columns.iter().map(print_name_ref).collect();
lines.push(format!(" GROUP {} TOTAL {}", columns.join(", "), print_name_ref(&group.total)));
}
lines.push(" ORDER BY".into());
for (index, item) in axis.order_by.iter().enumerate() {
let mut line = format!(" {} {}", print_name_ref(&item.column), item.direction.keyword());
if index + 1 < axis.order_by.len() {
line.push(',');
}
lines.push(line);
}
}
fn push_evaluate(lines: &mut Vec<String>, evaluate: &Evaluate) {
lines.push(format!("EVALUATE {}", print_expression(&evaluate.table)));
if !evaluate.order_by.is_empty() {
lines.push("ORDER BY".into());
for (index, item) in evaluate.order_by.iter().enumerate() {
let mut line = format!(" {} {}", print_expression(&item.expr), item.direction.keyword());
if index + 1 < evaluate.order_by.len() {
line.push(',');
}
lines.push(line);
}
}
if !evaluate.start_at.is_empty() {
let mut line = String::from("START AT ");
for (index, value) in evaluate.start_at.iter().enumerate() {
if index > 0 {
line.push_str(", ");
}
write_start_value(&mut line, value);
}
lines.push(line);
}
}
fn write_start_value(out: &mut String, value: &StartValue) {
match value {
StartValue::Literal(literal) => write_literal(out, literal),
StartValue::Parameter(name) => {
out.push('@');
out.push_str(&name.text);
}
}
}
fn write_quoted(out: &mut String, text: &str, quote: char) {
out.push(quote);
for c in text.chars() {
if c == quote {
out.push(quote);
}
out.push(c);
}
out.push(quote);
}
fn write_bracketed(out: &mut String, text: &str) {
out.push('[');
for c in text.chars() {
if c == ']' {
out.push(']');
}
out.push(c);
}
out.push(']');
}
fn write_name(out: &mut String, name: &Name) {
match name.style {
NameStyle::Bare => out.push_str(&name.text),
NameStyle::Quoted => write_quoted(out, &name.text, '\''),
NameStyle::Bracketed => write_bracketed(out, &name.text),
}
}
fn write_name_ref(out: &mut String, name: &NameRef) {
if let Some(table) = &name.table {
write_name(out, table);
}
write_name(out, &name.name);
}
fn write_literal(out: &mut String, literal: &Literal) {
match literal {
Literal::Integer(n) => {
let _ = write!(out, "{n}");
}
Literal::Decimal(n) => {
// `Debug` keeps a decimal point (`1000.0`) or an exponent (`1e300`) for every finite
// value, so the printed text re-lexes as a Decimal instead of an Integer.
let _ = write!(out, "{n:?}");
}
Literal::DateTime(value) => {
let _ = write!(out, "dt\"{value}\"");
}
Literal::String(s) => write_quoted(out, s, '"'),
Literal::Boolean(true) => out.push_str("TRUE"),
Literal::Boolean(false) => out.push_str("FALSE"),
}
}
fn write_call_head(out: &mut String, call: &Call) {
write_name(out, &call.name);
out.push('(');
}
/// One element of the printer's work stack. Expressions are expanded here rather than by
/// recursion; text tasks cover operators and separators.
enum Task<'a> {
Expr(&'a Expr, u8),
Text(&'static str),
Name(&'a Name),
}
fn write_expr(out: &mut String, root: &Expr, root_min_bp: u8) {
let mut stack: Vec<Task<'_>> = vec![Task::Expr(root, root_min_bp)];
while let Some(task) = stack.pop() {
match task {
Task::Text(text) => out.push_str(text),
Task::Name(name) => write_name(out, name),
Task::Expr(expr, min_bp) => match &expr.kind {
ExprKind::Literal(literal) => write_literal(out, literal),
ExprKind::Name(name) => write_name_ref(out, name),
ExprKind::Unary { op, expr } => {
let bp = op.precedence();
let parens = bp < min_bp;
if parens {
out.push('(');
stack.push(Task::Text(")"));
}
stack.push(Task::Expr(expr, bp));
if matches!(op, UnaryOp::Plus | UnaryOp::Neg) && matches!(expr.kind, ExprKind::Unary { op: UnaryOp::Plus | UnaryOp::Neg, .. }) {
// `--` would start a line comment; separate repeated signs.
stack.push(Task::Text(" "));
}
stack.push(Task::Text(match op {
UnaryOp::Plus => "+",
UnaryOp::Neg => "-",
UnaryOp::Not => "NOT ",
}));
}
ExprKind::Binary { op, left, right } => {
let bp = op.precedence();
let parens = bp < min_bp;
if parens {
out.push('(');
stack.push(Task::Text(")"));
}
let (left_min, right_min) = if op.is_right_associative() { (bp + 1, bp) } else { (bp, bp + 1) };
stack.push(Task::Expr(right, right_min));
stack.push(Task::Text(" "));
stack.push(Task::Text(op.symbol()));
stack.push(Task::Text(" "));
stack.push(Task::Expr(left, left_min));
}
ExprKind::Call(call) => {
write_call_head(out, call);
if call.args.is_empty() {
out.push(')');
} else {
stack.push(Task::Text(")"));
for (index, arg) in call.args.iter().enumerate().rev() {
stack.push(Task::Expr(arg, 0));
if index > 0 {
stack.push(Task::Text(", "));
}
}
}
}
ExprKind::Table(items) => {
out.push('{');
if items.is_empty() {
out.push('}');
} else {
out.push(' ');
stack.push(Task::Text(" }"));
for (index, item) in items.iter().enumerate().rev() {
stack.push(Task::Expr(item, 0));
if index > 0 {
stack.push(Task::Text(", "));
}
}
}
}
ExprKind::Tuple(items) => {
out.push('(');
if items.is_empty() {
out.push(')');
} else {
stack.push(Task::Text(")"));
for (index, item) in items.iter().enumerate().rev() {
stack.push(Task::Expr(item, 0));
if index > 0 {
stack.push(Task::Text(", "));
}
}
}
}
ExprKind::VarReturn { vars, body } => {
let parens = VAR_RETURN_BP < min_bp;
if parens {
out.push('(');
stack.push(Task::Text(")"));
}
stack.push(Task::Expr(body, 0));
stack.push(Task::Text("RETURN "));
for var in vars.iter().rev() {
stack.push(Task::Text(" "));
stack.push(Task::Expr(&var.expr, 0));
stack.push(Task::Text(" = "));
stack.push(Task::Name(&var.name));
stack.push(Task::Text("VAR "));
}
}
},
}
}
}
-75
View File
@@ -1,75 +0,0 @@
//! Model references as DAX text, and the formulas of Excel's implicit measures.
//!
//! The model window lists every visible column with a summarization, and a model PivotTable
//! summarizes a column the same way. Both spell the column the same way so the evaluator reads
//! them identically: this module owns the one spelling.
/// Reserved words the lexer or parser turns into operators and statement keywords: a table with
/// one of these names must be quoted, or `SUM(In[Amount])` would not parse.
const RESERVED: [&str; 7] = ["NOT", "IN", "EVALUATE", "VAR", "RETURN", "TRUE", "FALSE"];
/// A DAX table reference for a model name, quoted when the name is not a plain identifier or is a
/// reserved word.
pub fn table_ref(name: &str) -> String {
let plain = !name.is_empty()
&& name.chars().next().is_some_and(|c| c.is_alphabetic() || c == '_')
&& name.chars().all(|c| c.is_alphanumeric() || c == '_')
&& !RESERVED.iter().any(|word| word.eq_ignore_ascii_case(name));
if plain { name.to_string() } else { format!("'{}'", name.replace('\'', "''")) }
}
/// A DAX column reference for a model name; a `]` in the name is escaped as `]]`.
pub fn column_ref(name: &str) -> String {
format!("[{}]", name.replace(']', "]]"))
}
/// The formula Excel's implicit measure over `table[column]` evaluates, or `None` when
/// `aggregate` is not one of Excel's five summarizations.
///
/// `Count` is `COUNTA`, not `COUNT`: Excel counts the column's non-blank values whatever their
/// type, and `COUNT` ignores booleans — a `TRUE`/`FALSE` column would answer BLANK — while
/// `COUNTROWS` would count blanks too. `COUNTA` is the "non-blank values" rule the model window
/// and a model PivotTable show under `Count of <column>`.
pub fn implicit_measure_formula(aggregate: &str, table: &str, column: &str) -> Option<String> {
let function = match aggregate.trim().to_ascii_lowercase().as_str() {
"sum" => "SUM",
"average" => "AVERAGE",
"count" => "COUNTA",
"min" => "MIN",
"max" => "MAX",
_ => return None,
};
Some(format!("{function}({}{})", table_ref(table), column_ref(column)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn references_quote_what_dax_needs_quoted() {
assert_eq!(table_ref("Sales"), "Sales");
assert_eq!(table_ref("Sales Data"), "'Sales Data'");
assert_eq!(table_ref("O'Brien"), "'O''Brien'");
assert_eq!(table_ref("In"), "'In'");
assert_eq!(table_ref("VAR"), "'VAR'");
// A bare `TRUE`/`FALSE` would parse as a Boolean literal, not as a table.
assert_eq!(table_ref("TRUE"), "'TRUE'");
assert_eq!(table_ref("False"), "'False'");
assert_eq!(column_ref("Amount"), "[Amount]");
assert_eq!(column_ref("a]b"), "[a]]b]");
}
#[test]
fn implicit_measures_count_non_blank_values() {
assert_eq!(implicit_measure_formula("Sum", "Sales", "Amount"), Some("SUM(Sales[Amount])".to_string()));
// `Count` counts non-blank values of any type, so it maps to COUNTA: COUNT would ignore a
// boolean column and answer BLANK.
assert_eq!(implicit_measure_formula("count", "Sales Data", "Region"), Some("COUNTA('Sales Data'[Region])".to_string()));
assert_eq!(implicit_measure_formula("Count", "Sales", "IsPriority"), Some("COUNTA(Sales[IsPriority])".to_string()));
assert_eq!(implicit_measure_formula("Average", "Sales", "Amount"), Some("AVERAGE(Sales[Amount])".to_string()));
assert_eq!(implicit_measure_formula("Min", "Sales", "Amount"), Some("MIN(Sales[Amount])".to_string()));
assert_eq!(implicit_measure_formula("Max", "Sales", "Amount"), Some("MAX(Sales[Amount])".to_string()));
assert_eq!(implicit_measure_formula("None", "Sales", "Amount"), None);
}
}
File diff suppressed because it is too large Load Diff
-477
View File
@@ -1,477 +0,0 @@
use crate::ast::*;
use crate::lexer::TokenKind;
use crate::{MAX_DEPTH, MAX_INPUT_LEN, MAX_QUERY_LEN, parse_expression, parse_query, print_expression, print_query, tokenize};
fn expression(src: &str) -> Expr {
match parse_expression(src) {
Ok(expr) => expr,
Err(error) => panic!("{src:?} did not parse: {error}"),
}
}
/// Parses, prints, re-parses and asserts the AST is unchanged. Returns the canonical text.
fn round_trip(src: &str) -> String {
let parsed = expression(src);
let printed = print_expression(&parsed);
let reparsed = match parse_expression(&printed) {
Ok(expr) => expr,
Err(error) => panic!("canonical text {printed:?} did not parse: {error}"),
};
assert_eq!(parsed, reparsed, "round trip changed the AST for {src:?} via {printed:?}");
printed
}
fn binary(expr: &Expr) -> (&BinaryOp, &Expr, &Expr) {
match &expr.kind {
ExprKind::Binary { op, left, right } => (op, left, right),
other => panic!("expected a binary expression, found {other:?}"),
}
}
#[test]
fn every_operator_spelling_and_canonical_text() {
for (src, canonical) in [
("1 + 2", "1 + 2"),
("1 - 2", "1 - 2"),
("1 * 2", "1 * 2"),
("1 / 2", "1 / 2"),
("1 ^ 2", "1 ^ 2"),
("\"a\" & \"b\"", "\"a\" & \"b\""),
("1 = 2", "1 = 2"),
("1 == 2", "1 == 2"),
("1 <> 2", "1 <> 2"),
("1 < 2", "1 < 2"),
("1 > 2", "1 > 2"),
("1 <= 2", "1 <= 2"),
("1 >= 2", "1 >= 2"),
("TRUE && FALSE", "TRUE && FALSE"),
("TRUE || FALSE", "TRUE || FALSE"),
("NOT TRUE", "NOT TRUE"),
("1 IN { 1 }", "1 IN { 1 }"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
}
#[test]
fn arithmetic_precedence_parentheses_and_associativity() {
for (src, canonical) in [
("1 + 2 * 3", "1 + 2 * 3"),
("1 * 2 + 3", "1 * 2 + 3"),
("1 + 2 / 3", "1 + 2 / 3"),
("1 - 2 * 3", "1 - 2 * 3"),
("1 / 2 - 3", "1 / 2 - 3"),
("1 + 2 - 3", "1 + 2 - 3"),
("1 - 2 + 3", "1 - 2 + 3"),
("1 * 2 / 3", "1 * 2 / 3"),
("1 / 2 * 3", "1 / 2 * 3"),
("1 + 2 + 3", "1 + 2 + 3"),
("1 - 2 - 3", "1 - 2 - 3"),
("1 * 2 * 3", "1 * 2 * 3"),
("1 / 2 / 3", "1 / 2 / 3"),
("(1 + 2) * 3", "(1 + 2) * 3"),
("1 * (2 + 3)", "1 * (2 + 3)"),
("1 - (2 - 3)", "1 - (2 - 3)"),
("((1))", "1"),
("(1 + 2)", "1 + 2"),
("2 ^ 3 * 4", "2 ^ 3 * 4"),
("2 * 3 ^ 4", "2 * 3 ^ 4"),
("2 ^ 3 + 4", "2 ^ 3 + 4"),
("2 ^ 3 ^ 2", "2 ^ 3 ^ 2"),
("(2 ^ 3) ^ 2", "2 ^ 3 ^ 2"),
("2 ^ (3 ^ 2)", "2 ^ (3 ^ 2)"),
("-2 ^ 2", "-2 ^ 2"),
("(-2) ^ 2", "(-2) ^ 2"),
("2 ^ -3", "2 ^ (-3)"),
("2 ^ (-3)", "2 ^ (-3)"),
("-(2 * 3)", "-(2 * 3)"),
("-2 * 3", "-2 * 3"),
("+1 - 2", "+1 - 2"),
("1 + -2", "1 + -2"),
("1 - -2", "1 - -2"),
("- -2", "- -2"),
("- +2", "- +2"),
("+ -2", "+ -2"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
let expr = expression("-2 ^ 2");
assert!(matches!(&expr.kind, ExprKind::Unary { op: UnaryOp::Neg, expr: inner }
if matches!(&inner.kind, ExprKind::Binary { op: BinaryOp::Pow, .. })));
let expr = expression("(-2) ^ 2");
let (op, left, _) = binary(&expr);
assert_eq!(*op, BinaryOp::Pow);
assert!(matches!(&left.kind, ExprKind::Unary { op: UnaryOp::Neg, .. }));
}
#[test]
fn binary_operators_associate_left() {
let expr = expression("1 - 2 - 3");
let (op, left, right) = binary(&expr);
assert_eq!(*op, BinaryOp::Sub);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Sub, .. }));
assert!(matches!(&right.kind, ExprKind::Literal(Literal::Integer(n)) if *n == 3));
// DAX orders equal precedence left to right, so a `^` chain groups left: `(2^3)^2`.
let expr = expression("2 ^ 3 ^ 2");
let (op, left, right) = binary(&expr);
assert_eq!(*op, BinaryOp::Pow);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Pow, .. }));
assert!(matches!(&right.kind, ExprKind::Literal(Literal::Integer(n)) if *n == 2));
let expr = expression("1 / 2 / 3");
let (op, left, _) = binary(&expr);
assert_eq!(*op, BinaryOp::Div);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Div, .. }));
let expr = expression("1 - (2 - 3)");
let (op, _, right) = binary(&expr);
assert_eq!(*op, BinaryOp::Sub);
assert!(matches!(&right.kind, ExprKind::Binary { op: BinaryOp::Sub, .. }));
}
#[test]
fn comparison_and_concatenation_precedence() {
for (src, canonical) in [
("1 = 2", "1 = 2"),
("1 == 2", "1 == 2"),
("1 <> 2", "1 <> 2"),
("1 < 2", "1 < 2"),
("1 > 2", "1 > 2"),
("1 <= 2", "1 <= 2"),
("1 >= 2", "1 >= 2"),
("1 = 2 == 3", "1 = 2 == 3"),
("\"a\" & \"b\" = \"ab\"", "\"a\" & \"b\" = \"ab\""),
("\"a\" & (\"b\" = \"c\")", "\"a\" & (\"b\" = \"c\")"),
("\"a\" & \"b\" & \"c\"", "\"a\" & \"b\" & \"c\""),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
let expr = expression("1 = 2");
assert_eq!(*binary(&expr).0, BinaryOp::Eq);
let expr = expression("1 == 2");
assert_eq!(*binary(&expr).0, BinaryOp::StrictEq);
let expr = expression("1 = 2 == 3");
let (op, left, _) = binary(&expr);
assert_eq!(*op, BinaryOp::StrictEq);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Eq, .. }));
let expr = expression("\"a\" & \"b\" = \"ab\"");
let (op, left, _) = binary(&expr);
assert_eq!(*op, BinaryOp::Eq);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Concat, .. }));
}
#[test]
fn logical_operators_and_not_precedence() {
for (src, canonical) in [
("NOT TRUE", "NOT TRUE"),
("not false", "NOT FALSE"),
("TRUE && FALSE", "TRUE && FALSE"),
("TRUE || FALSE", "TRUE || FALSE"),
("NOT TRUE || FALSE && TRUE", "NOT TRUE || FALSE && TRUE"),
("TRUE && FALSE || TRUE", "TRUE && FALSE || TRUE"),
("TRUE || FALSE && TRUE", "TRUE || FALSE && TRUE"),
("NOT TRUE = FALSE", "NOT TRUE = FALSE"),
("NOT (TRUE = FALSE)", "NOT TRUE = FALSE"),
("NOT TRUE && FALSE", "NOT TRUE && FALSE"),
("NOT (TRUE && FALSE)", "NOT (TRUE && FALSE)"),
("NOT NOT TRUE", "NOT NOT TRUE"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
let expr = expression("TRUE || FALSE && TRUE");
let (op, left, right) = binary(&expr);
assert_eq!(*op, BinaryOp::Or);
assert!(matches!(&left.kind, ExprKind::Literal(Literal::Boolean(true))));
assert!(matches!(&right.kind, ExprKind::Binary { op: BinaryOp::And, .. }));
let expr = expression("NOT TRUE && FALSE");
let (op, left, _) = binary(&expr);
assert_eq!(*op, BinaryOp::And);
assert!(matches!(&left.kind, ExprKind::Unary { op: UnaryOp::Not, .. }));
let expr = expression("NOT TRUE = FALSE");
assert!(matches!(&expr.kind, ExprKind::Unary { op: UnaryOp::Not, expr: inner }
if matches!(&inner.kind, ExprKind::Binary { op: BinaryOp::Eq, .. })));
let expr = expression("NOT (TRUE && FALSE)");
assert!(matches!(&expr.kind, ExprKind::Unary { op: UnaryOp::Not, expr: inner }
if matches!(&inner.kind, ExprKind::Binary { op: BinaryOp::And, .. })));
}
#[test]
fn in_operator_with_lists_and_table_expressions() {
for (src, canonical) in [
("1 IN { 1 }", "1 IN { 1 }"),
("1 IN {1, 2, 3}", "1 IN { 1, 2, 3 }"),
("1 IN {}", "1 IN {}"),
("'Sales'[Region] IN { \"East\", \"West\" }", "'Sales'[Region] IN { \"East\", \"West\" }"),
("1 IN VALUES(T[Col])", "1 IN VALUES(T[Col])"),
("1 IN (FILTER(T, T[X] > 0))", "1 IN FILTER(T, T[X] > 0)"),
("1 IN { 1 } = TRUE", "1 IN { 1 } = TRUE"),
("2 ^ 3 IN { 8 }", "2 ^ 3 IN { 8 }"),
("1 + 2 IN { 3 }", "1 + 2 IN { 3 }"),
("-1 IN { 1 }", "-1 IN { 1 }"),
("NOT 1 IN { 1 }", "NOT 1 IN { 1 }"),
("1 IN { 1 } IN { TRUE }", "1 IN { 1 } IN { TRUE }"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
let expr = expression("1 IN { 1, 2 }");
let (_, _, right) = binary(&expr);
assert!(matches!(&right.kind, ExprKind::Table(items) if items.len() == 2));
let expr = expression("1 IN VALUES(T[Col])");
let (_, _, right) = binary(&expr);
assert!(matches!(&right.kind, ExprKind::Call(_)));
// `IN` sits in the comparison tier of Microsoft's operator table, so the arithmetic on its
// left is grouped first and `IN` is the outermost operator.
let expr = expression("2 ^ 3 IN { 8 }");
let (op, left, right) = binary(&expr);
assert_eq!(*op, BinaryOp::In);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Pow, .. }));
assert!(matches!(&right.kind, ExprKind::Table(_)));
let expr = expression("1 + 2 IN { 3 }");
let (op, left, right) = binary(&expr);
assert_eq!(*op, BinaryOp::In);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Add, .. }));
assert!(matches!(&right.kind, ExprKind::Table(_)));
// `IN` and `=` share the tier, so they group left to right.
let expr = expression("1 IN { 1 } = TRUE");
let (op, left, _) = binary(&expr);
assert_eq!(*op, BinaryOp::Eq);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::In, .. }));
let expr = expression("1 = 1 IN { TRUE }");
let (op, left, _) = binary(&expr);
assert_eq!(*op, BinaryOp::In);
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Eq, .. }));
}
#[test]
fn quoted_and_bracketed_identifiers_preserve_escapes() {
for (src, canonical) in [
("'My Table'[Sales Amount]", "'My Table'[Sales Amount]"),
("'It''s'[A]]B]", "'It''s'[A]]B]"),
("Sales[Amount]", "Sales[Amount]"),
("[Measure]", "[Measure]"),
("'Quoted Table'", "'Quoted Table'"),
("SUM('Sales'[Amount])", "SUM('Sales'[Amount])"),
("'Sales'[Amount] + 1", "'Sales'[Amount] + 1"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
let expr = expression("'It''s'[A]]B]");
match expr.kind {
ExprKind::Name(name) => {
let table = match &name.table {
Some(table) => table,
None => panic!("expected a table qualifier"),
};
assert_eq!(table.text, "It's");
assert_eq!(table.style, NameStyle::Quoted);
assert_eq!(name.name.text, "A]B");
assert_eq!(name.name.style, NameStyle::Bracketed);
}
other => panic!("expected a name, found {other:?}"),
}
}
#[test]
fn strings_numbers_booleans_and_calls() {
for (src, canonical) in [
("\"a\"\"b\"", "\"a\"\"b\""),
("\"\"", "\"\""),
("TRUE", "TRUE"),
("true", "TRUE"),
("False", "FALSE"),
("1", "1"),
("1.5", "1.5"),
(".5", "0.5"),
("1.", "1.0"),
("1e3", "1000.0"),
("1.5E-3", "0.0015"),
("0.000001", "1e-6"),
("0", "0"),
("1000", "1000"),
("SUM()", "SUM()"),
("SUM(1, 2)", "SUM(1, 2)"),
("SUM(1, MAX(2, 3))", "SUM(1, MAX(2, 3))"),
("Sum(1, 2)", "Sum(1, 2)"),
("STDEV.P(1, 2)", "STDEV.P(1, 2)"),
("TRUE()", "TRUE()"),
("true()", "true()"),
("FALSE(1)", "FALSE(1)"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
match expression("\"a\"\"b\"").kind {
ExprKind::Literal(Literal::String(text)) => assert_eq!(text, "a\"b"),
other => panic!("expected a string literal, found {other:?}"),
}
assert!(matches!(expression("TRUE").kind, ExprKind::Literal(Literal::Boolean(true))));
assert!(matches!(expression("FALSE").kind, ExprKind::Literal(Literal::Boolean(false))));
}
#[test]
fn table_and_row_constructors() {
for (src, canonical) in [
("{}", "{}"),
("{1}", "{ 1 }"),
("{1, 2, 3}", "{ 1, 2, 3 }"),
("{(1, 2), (3, 4)}", "{ (1, 2), (3, 4) }"),
("{ (\"a\", TRUE), (\"b\", FALSE) }", "{ (\"a\", TRUE), (\"b\", FALSE) }"),
("(1, 2)", "(1, 2)"),
("(1, 2, 3)", "(1, 2, 3)"),
("((1, 2))", "(1, 2)"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
let expr = expression("{ (1, \"a\"), (2, \"b\") }");
match expr.kind {
ExprKind::Table(rows) => {
assert_eq!(rows.len(), 2);
assert!(rows.iter().all(|row| matches!(&row.kind, ExprKind::Tuple(items) if items.len() == 2)));
}
other => panic!("expected a table, found {other:?}"),
}
}
#[test]
fn comments_are_skipped() {
for (src, canonical) in [
("1 + /* comment */ 2", "1 + 2"),
("1 + // comment\n2", "1 + 2"),
("1 + -- comment\n2", "1 + 2"),
("/* lead */ 1 /* tail */", "1"),
("1--2", "1"),
("1 - -2", "1 - -2"),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
}
#[test]
fn query_parsing_and_printing() {
let query = parse_query("EVALUATE SUM('Sales'[Amount])").unwrap();
assert!(query.define.is_none());
assert_eq!(query.evaluates.len(), 1);
assert_eq!(print_query(&query), "EVALUATE SUM('Sales'[Amount])");
assert_eq!(parse_query(&print_query(&query)).unwrap(), query);
assert_eq!(print_query(&parse_query("evaluate 1 + 2 * 3").unwrap()), "EVALUATE 1 + 2 * 3");
assert_eq!(print_query(&parse_query("/* c */ EVALUATE {1, 2}").unwrap()), "EVALUATE { 1, 2 }");
for bad in ["", "1 + 2", "EVALUATE", "EVALUATE 1 2", "EVALUATE 1 +"] {
assert!(parse_query(bad).is_err(), "expected a query error for {bad:?}");
}
}
#[test]
fn leading_equals_is_accepted_for_expressions() {
assert_eq!(round_trip("= 1 + 2"), "1 + 2");
assert!(parse_expression("=").is_err());
}
#[test]
fn malformed_input_reports_errors() {
for bad in [
"", " ", "(", "()", "(1,", "(1,)", "{1,", "{1, }", "1 +", "1 2", "1e", "1e+", "1.2.3", "123abc", "\"abc", "'abc", "[abc", "/* abc", "1 IN",
"NOT", "1 == ", "1 & ", "=>", "1 => 2", "SUM(1,)", "SUM(1", "SUM(,1)", "1 ? 2", "=", "''", "1 | 2",
] {
assert!(parse_expression(bad).is_err(), "expected an error for {bad:?}");
}
}
#[test]
fn error_spans_point_at_the_problem() {
let error = parse_expression("1 + )").unwrap_err();
assert_eq!(error.span, Span::new(4, 5));
assert!(error.to_string().contains("bytes 4..5"), "{error}");
let error = parse_expression("\"abc").unwrap_err();
assert_eq!(error.span, Span::new(0, 4));
let error = parse_expression("1 + ").unwrap_err();
assert_eq!(error.span, Span::new(4, 4));
}
#[test]
fn nesting_and_input_length_are_bounded() {
let deep = format!("{}1{}", "(".repeat(MAX_DEPTH + 4), ")".repeat(MAX_DEPTH + 4));
let error = parse_expression(&deep).unwrap_err();
assert!(error.message.contains("nested too deeply"), "{}", error.message);
let shallow = format!("{}1{}", "(".repeat(100), ")".repeat(100));
assert_eq!(round_trip(&shallow), "1");
let long = "1".repeat(MAX_INPUT_LEN + 1);
let error = parse_expression(&long).unwrap_err();
assert!(error.message.contains("too long"), "{}", error.message);
// Tokenizing itself is unbounded; only the expression/query entrypoints apply limits.
assert!(tokenize(&" ".repeat(MAX_INPUT_LEN + 1)).is_ok());
let long_query = format!("EVALUATE ROW({})", vec!["\"A\", 1"; 1_200].join(", "));
assert!(long_query.len() > MAX_INPUT_LEN && long_query.len() < MAX_QUERY_LEN);
assert!(parse_query(&long_query).is_ok(), "queries may exceed the expression limit");
let huge_query = " ".repeat(MAX_QUERY_LEN + 1);
assert!(parse_query(&huge_query).unwrap_err().message.contains("query is too long"));
let chain = vec!["1"; 1_000].join(" + ");
assert!(chain.len() < MAX_INPUT_LEN);
assert!(parse_expression(&chain).is_err(), "a 1,000-term chain exceeds the nesting limit");
let short = vec!["1"; 200].join(" + ");
assert_eq!(round_trip(&short), short);
// A flat list of sibling expressions must not accumulate the depth of their internal
// binary folds.
let args = (0..300).map(|i| format!("{i} + 1")).collect::<Vec<_>>().join(", ");
let call = format!("ROW({args})");
assert!(call.len() < MAX_INPUT_LEN);
assert!(parse_expression(&call).is_ok());
// Parentheses disappear from the AST, so a grouped chain keeps its depth; adding more
// folds around it must still hit the limit.
let inner = vec!["1"; 200].join(" + ");
let outer = format!("({inner}) + {}", vec!["1"; 100].join(" + "));
assert!(outer.len() < MAX_INPUT_LEN);
assert!(parse_expression(&outer).is_err(), "a grouped 300-term chain exceeds the nesting limit");
let ok_inner = vec!["1"; 100].join(" + ");
let ok_outer = format!("({ok_inner}) + {}", vec!["1"; 100].join(" + "));
assert!(parse_expression(&ok_outer).is_ok());
}
#[test]
fn spans_are_byte_offsets_and_ignored_by_ast_equality() {
let expr = expression("1 + 23");
assert_eq!(expr.span, Span::new(0, 6));
let (_, left, right) = binary(&expr);
assert_eq!(left.span, Span::new(0, 1));
assert_eq!(right.span, Span::new(4, 6));
assert_eq!(expression("1 + 2"), expression(" 1 + 2 "));
}
#[test]
fn lexer_tokens_keywords_and_arrow() {
let tokens = tokenize("NOT true").unwrap();
assert_eq!(tokens.first().map(|t| &t.kind), Some(&TokenKind::Not));
assert_eq!(tokens.get(1).map(|t| &t.kind), Some(&TokenKind::Ident("true".into())));
assert_eq!(tokens.get(2).map(|t| &t.kind), Some(&TokenKind::Eof));
let tokens = tokenize("x => y").unwrap();
assert_eq!(tokens.get(1).map(|t| &t.kind), Some(&TokenKind::Arrow));
let tokens = tokenize("value in {1}").unwrap();
assert_eq!(tokens.get(1).map(|t| &t.kind), Some(&TokenKind::In));
}
-741
View File
@@ -1,741 +0,0 @@
//! DAX data types, literal classification, static inference and operator result tables.
//!
//! The eight scalar types are [`DataType`]'s variants, matching
//! <https://dax.guide/datatypes/>: Binary, Boolean, Currency, DateTime, Decimal, Integer,
//! String and Variant. [`PseudoType`] adds `BLANK` and `Table`, which Microsoft documents as DAX
//! types but dax.guide does not list among the eight. They are inference results, not members of
//! [`DataType`].
//!
//! # Parser-level versus evaluator-level
//!
//! This module is static. It classifies literals, infers types for expressions built from
//! literals and operators, and reports clearly incompatible operands from the documented
//! operator tables. It never evaluates an expression.
//!
//! The following belong to the evaluator and are deliberately absent:
//!
//! - text-to-number, text-to-date and text-to-Boolean parsing, and the conversion errors when
//! text is not numeric (`"22" + 22` succeeds only when the text parses);
//! - BLANK substitution, the BLANK truth tables, `0/BLANK` (NaN) and `5/BLANK` (Infinity);
//! - Currency rounding/truncation and the fixed-point versus floating-point rules for `*` and
//! `/`;
//! - integer overflow at runtime (literal overflow is a lexer error);
//! - IEEE-754 precision and equality (`0.1 + 0.2 = 0.3` can be false);
//! - string collation, case folding and trailing-space trimming;
//! - date normalization in `DATE`/`TIME`, date subtraction at runtime, and Variant dispatch.
//!
//! # Documented conflicts
//!
//! The published rules are not one consistent lattice; this module preserves the operator
//! tables instead of "fixing" them:
//!
//! - `*` is documented as `Integer * DateTime -> Integer` and `Currency * DateTime ->
//! Currency`, although no DateTime row exists in the source table. The table is reproduced
//! cell for cell; a DateTime on the left of `*` is reported as a type error.
//! - Subtraction of two DateTimes is documented as DateTime, while engines commonly produce a
//! day count. The documented cell is used and the discrepancy is noted in [`TypeMetadata`].
//! - Microsoft's comparison pages both say text is not compared with numbers (an error) and
//! that a Boolean > String > numeric type rank makes such comparisons succeed. The operator
//! reference's "error" rule is modelled: comparing String with a numeric type is a
//! [`TypeError`]. String comparisons are case-insensitive and accent-sensitive at runtime.
//! - Currency and Integer endpoint documentation disagree. The ranges recorded in
//! [`TypeMetadata`] name the disagreement instead of picking a silent winner.
//! - Excel's embedded engine rejects `==`; dax.guide documents it and this crate parses it.
//! Strict equality is still modelled here: `==` does not coerce BLANK.
//! - `dt"..."` literals are a Power BI/SSAS feature (August 2021 onwards) and are not supported
//! by every engine version, despite being documented DAX syntax.
use std::fmt;
use crate::ast::{BinaryOp, Call, Expr, ExprKind, Literal, UnaryOp};
/// The eight scalar DAX data types, in dax.guide's listing order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DataType {
Binary,
Boolean,
Currency,
DateTime,
Decimal,
Integer,
String,
Variant,
}
impl DataType {
/// Every scalar type, in dax.guide's listing order.
pub const ALL: [DataType; 8] = [
DataType::Binary,
DataType::Boolean,
DataType::Currency,
DataType::DateTime,
DataType::Decimal,
DataType::Integer,
DataType::String,
DataType::Variant,
];
/// The type's canonical display name.
pub const fn name(self) -> &'static str {
match self {
DataType::Binary => "Binary",
DataType::Boolean => "Boolean",
DataType::Currency => "Currency",
DataType::DateTime => "DateTime",
DataType::Decimal => "Decimal",
DataType::Integer => "Integer",
DataType::String => "String",
DataType::Variant => "Variant",
}
}
/// Representation, literal availability, range, precision and notes.
pub const fn metadata(self) -> TypeMetadata {
match self {
DataType::Binary => TypeMetadata {
name: "Binary",
representation: "opaque byte sequence; not usable as a DAX expression value",
literal_syntax: None,
range: "up to 67,108,864 bytes per value in SSAS tabular; unsupported in Power BI models",
precision: "opaque bytes",
notes: "A model-only type. No DAX operator or function produces or consumes Binary, so it is inert for tokenizing, parsing and typing.",
},
DataType::Boolean => TypeMetadata {
name: "Boolean",
representation: "TRUE or FALSE, nullable",
literal_syntax: Some("TRUE | FALSE (case-insensitive); TRUE() and FALSE() are equivalent calls"),
range: "TRUE, FALSE",
precision: "exact",
notes: "TRUE is 1 and FALSE is 0 when a numeric operator needs a number (TRUE + 1 = 2), but comparisons only pair Boolean with Boolean. BLANK is coerced to FALSE for =, not for ==.",
},
DataType::Currency => TypeMetadata {
name: "Currency",
representation: "64-bit signed integer scaled by 10,000 (fixed four decimal places)",
literal_syntax: None,
range: "about -922,337,203,685,477.5807 to 922,337,203,685,477.5807; Power BI, SSAS and Excel documentation disagree at the endpoints",
precision: "four decimal places, 19 significant digits",
notes: "No literal. Produced by Currency columns, CURRENCY() and CONVERT(..., CURRENCY) (where DECIMAL is an alias for Currency), plus aggregation over Currency columns. Addition and subtraction keep fixed-point rules; multiplication and division may yield a floating-point result.",
},
DataType::DateTime => TypeMetadata {
name: "DateTime",
representation: "double: whole days since 1899-12-30, fraction is the time of day",
literal_syntax: Some("dt\"YYYY-MM-DD\", dt\"YYYY-MM-DDThh:mm:ss\" or dt\"YYYY-MM-DD hh:mm:ss\""),
range: "serial 0 is 1899-12-30; maximum is 9999-12-31 00:00:00. Engine support before 1900-03-01 is documented as unreliable, and minimum-date documentation conflicts",
precision: "Power BI stores time at 1/300 second (3.33 ms)",
notes: "dt literals were introduced in Power BI Desktop (August 2021) and later in AS/Power Pivot, so not every engine version accepts them. Locale-sensitive text parsing uses DATEVALUE/TIMEVALUE and belongs to the evaluator. Two dates subtracted are documented as DateTime even though engines commonly return a day count.",
},
DataType::Decimal => TypeMetadata {
name: "Decimal",
representation: "IEEE-754 64-bit double (TOM Double / SQL Float)",
literal_syntax: Some("digits with a decimal point or exponent: 3.14, .5, 1., 1e3; the sign is the unary operator"),
range: "-1.79e308 to 1.79e308; NaN and Infinity can result from operations but have no literals",
precision: "approximately 15-17 significant digits; values are approximate",
notes: "Division always yields Decimal, including Integer/Integer. Equality is sensitive to binary representation, so compare with tolerance where appropriate. Integer or Currency arithmetic that promotes yields Decimal.",
},
DataType::Integer => TypeMetadata {
name: "Integer",
representation: "64-bit signed integer (Int64)",
literal_syntax: Some("digit sequence such as 42; the sign is the unary operator"),
range: "-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (i64). SSAS documents a narrower range because the endpoints are reserved as null sentinels",
precision: "exact",
notes: "There is no integer division: / always yields Decimal. Literal overflow is a lexer error; runtime overflow is an evaluator concern. The literal i64::MIN cannot be written, because the sign is a unary operator and its unsigned magnitude overflows.",
},
DataType::String => TypeMetadata {
name: "String",
representation: "UTF-16 Unicode text",
literal_syntax: Some("\"text\" with doubled quotes, e.g. \"Say \"\"hi\"\"\""),
range: "engine-dependent; about 32,000 characters in Power BI and larger in the Excel Data Model",
precision: "Unicode characters; trailing spaces are trimmed by the engine, leading spaces are significant",
notes: "The empty string \"\" is not BLANK. Comparison is case-insensitive and accent-sensitive in the engine. Text is not implicitly compared with numbers (the engine errors), but numeric text participates in arithmetic when it parses.",
},
DataType::Variant => TypeMetadata {
name: "Variant",
representation: "runtime-tagged scalar: Boolean, Integer, Currency, Decimal, DateTime, String or BLANK",
literal_syntax: None,
range: "the union of the scalar types",
precision: "depends on the runtime type",
notes: "Produced by expressions with mixed-type branches (IF, SWITCH, COALESCE) and some measures. Not a column type in a regular table, and Microsoft's syntax page states DAX does not support Variant; dax.guide and SSAS clarify that expression-level Variant exists. No literal and no operators of its own.",
},
}
}
/// Integer, Currency and Decimal are the numeric types (Boolean coerces to 1/0 in numeric
/// operators but is not itself numeric).
pub const fn is_numeric(self) -> bool {
matches!(self, DataType::Integer | DataType::Currency | DataType::Decimal)
}
/// Whether a literal of this type can be written in DAX.
pub const fn has_literal(self) -> bool {
self.metadata().literal_syntax.is_some()
}
}
/// `BLANK` and `Table` are DAX types in Microsoft's documentation but not members of
/// dax.guide's eight-type list. They are inference results, never [`DataType`] values.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PseudoType {
Blank,
Table,
}
impl PseudoType {
pub const ALL: [PseudoType; 2] = [PseudoType::Blank, PseudoType::Table];
pub const fn name(self) -> &'static str {
match self {
PseudoType::Blank => "BLANK",
PseudoType::Table => "Table",
}
}
pub const fn metadata(self) -> TypeMetadata {
match self {
PseudoType::Blank => TypeMetadata {
name: "BLANK",
representation: "the absence of a value; distinct from 0, \"\" and FALSE",
literal_syntax: None,
range: "not applicable",
precision: "not applicable",
notes: "There is no BLANK literal: BLANK() is a zero-argument function. Polymorphic: BLANK()+5 = 5, BLANK()*5 = BLANK, BLANK()=0 is TRUE. Do not silently treat BLANK as Integer; coercion depends on the operator and the other operand.",
},
PseudoType::Table => TypeMetadata {
name: "Table",
representation: "a set of rows and columns; non-scalar",
literal_syntax: Some("table constructor { value, ... } or { (value, ...), ... }, plus table references"),
range: "not applicable",
precision: "not applicable",
notes: "DAX has no row-value type: ROW(...) returns a one-row table. A single-column single-row table may be used as a scalar in an expression context; that is a type-checking special case, not a literal rule.",
},
}
}
}
/// One row of type documentation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TypeMetadata {
/// Display name (`Integer`, `BLANK`, `Table`).
pub name: &'static str,
/// Internal or model representation.
pub representation: &'static str,
/// The literal syntax, or `None` when the type has no literal.
pub literal_syntax: Option<&'static str>,
/// Documented range, including conflicting endpoints where they exist.
pub range: &'static str,
/// Documented precision.
pub precision: &'static str,
/// Behaviour a static type checker cannot model.
pub notes: &'static str,
}
/// The result of static type inference.
///
/// [`InferredType::Unknown`] is not a DAX type: it means the expression's type depends on the
/// model, a column, a measure or a function catalog. It is distinct from
/// [`InferredType::Data(DataType::Variant)`], which is a real expression-level DAX type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InferredType {
Data(DataType),
Blank,
Table,
Unknown,
}
impl InferredType {
pub const fn name(self) -> &'static str {
match self {
InferredType::Data(data_type) => data_type.name(),
InferredType::Blank => "BLANK",
InferredType::Table => "Table",
InferredType::Unknown => "unknown",
}
}
pub const fn data(self) -> Option<DataType> {
match self {
InferredType::Data(data_type) => Some(data_type),
InferredType::Blank | InferredType::Table | InferredType::Unknown => None,
}
}
}
impl From<DataType> for InferredType {
fn from(value: DataType) -> Self {
InferredType::Data(value)
}
}
impl From<PseudoType> for InferredType {
fn from(value: PseudoType) -> Self {
match value {
PseudoType::Blank => InferredType::Blank,
PseudoType::Table => InferredType::Table,
}
}
}
/// A static type error: operators applied to operands with no documented result type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TypeError {
/// The binary operator has no result for these operands, or was used with the wrong kind
/// of API (for example `Eq` passed to [`arithmetic_type`]).
IncompatibleOperands { op: BinaryOp, left: InferredType, right: InferredType },
/// Unary `+`, `-` or `NOT` cannot be applied to this operand.
IncompatibleUnaryOperand { op: UnaryOp, operand: InferredType },
/// Two values have no documented common comparison type (used by
/// [`comparison_coercion`], which takes no operator).
IncompatibleTypes { left: InferredType, right: InferredType },
}
impl fmt::Display for TypeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TypeError::IncompatibleOperands { op, left, right } => {
write!(f, "operator `{}` cannot combine {} and {}", op.symbol(), left.name(), right.name())
}
TypeError::IncompatibleUnaryOperand { op, operand } => {
write!(f, "unary operator `{}` cannot be applied to {}", op.symbol(), operand.name())
}
TypeError::IncompatibleTypes { left, right } => {
write!(f, "types {} and {} have no common comparison type", left.name(), right.name())
}
}
}
}
impl std::error::Error for TypeError {}
/// Classifies a literal. Every literal form maps to one of the eight scalar types; BLANK has
/// no literal form.
pub const fn literal_type(literal: &Literal) -> DataType {
match literal {
Literal::Integer(_) => DataType::Integer,
Literal::Decimal(_) => DataType::Decimal,
Literal::DateTime(_) => DataType::DateTime,
Literal::String(_) => DataType::String,
Literal::Boolean(_) => DataType::Boolean,
}
}
/// A scalar operand's type: a table-valued call may still resolve to a single row/column at
/// evaluation time (`LASTDATE('Date'[Date]) - 1`), so it is unknown here rather than a table.
fn scalar_operand(expr: &Expr) -> Result<InferredType, TypeError> {
let inferred = infer_type(expr)?;
// A `VAR`/`RETURN` block is transparent for this check: its body is what the operator sees,
// so `(VAR d = 1 RETURN LASTDATE('Date'[Date])) - 1` is the same table-valued operand as the
// unwrapped call and must be rejected identically.
let mut inner = expr;
while let ExprKind::VarReturn { body, .. } = &inner.kind {
inner = body;
}
Ok(if inferred == InferredType::Table && matches!(&inner.kind, ExprKind::Call(_)) { InferredType::Unknown } else { inferred })
}
/// Infers the static type of an expression.
///
/// Name references are [`InferredType::Unknown`] (they need the model). Catalogued calls take
/// their documented [`crate::functions::ReturnType`]; unknown functions and `Any`/`Numeric`
/// return types stay unknown. Incompatible known operands produce a [`TypeError`].
pub fn infer_type(expr: &Expr) -> Result<InferredType, TypeError> {
match &expr.kind {
ExprKind::Literal(literal) => Ok(InferredType::Data(literal_type(literal))),
ExprKind::Name(_) => Ok(InferredType::Unknown),
ExprKind::Call(call) => {
// The call itself may be unknown without a signature catalog, but every argument
// still has to type-check.
for arg in &call.args {
infer_type(arg)?;
}
Ok(call_type(call))
}
ExprKind::Unary { op, expr } => {
let operand = scalar_operand(expr)?;
unary_type(*op, operand)
}
ExprKind::Binary { op, left, right } => {
// `(a, b) IN { (a, b), ... }` uses a row constructor on the left, not a table
// expression. Validate its elements but let the operator comparison handle the
// row value.
let left = match (&left.kind, op) {
(ExprKind::Tuple(items), BinaryOp::In) => {
for item in items {
infer_type(item)?;
}
InferredType::Unknown
}
_ if *op == BinaryOp::In => infer_type(left)?,
_ => scalar_operand(left)?,
};
let right = if *op == BinaryOp::In { infer_type(right)? } else { scalar_operand(right)? };
binary_type(*op, left, right)
}
ExprKind::Table(items) | ExprKind::Tuple(items) => {
// Containers are tables, but their elements still have to type-check.
for item in items {
infer_type(item)?;
}
Ok(InferredType::Table)
}
// Variable references are names, so their values are unknown without an environment; the
// block's type is the type of its `RETURN` expression. Every declaration still has to
// type-check, even when the body does not use it.
ExprKind::VarReturn { vars, body } => {
for var in vars {
infer_type(&var.expr)?;
}
infer_type(body)
}
}
}
/// The documented return type of a catalogued function, mapped onto the static type model.
///
/// `Numeric` stays [`InferredType::Unknown`] because its concrete type (Integer, Currency or
/// Decimal) follows the inputs; `Any`/unknown signatures stay unknown as well.
fn call_type(call: &Call) -> InferredType {
if call.args.is_empty() {
if call.name.text.eq_ignore_ascii_case("TRUE") || call.name.text.eq_ignore_ascii_case("FALSE") {
return InferredType::Data(DataType::Boolean);
}
if call.name.text.eq_ignore_ascii_case("BLANK") {
return InferredType::Blank;
}
}
let Some(spec) = crate::functions::lookup(&call.name.text) else {
return InferredType::Unknown;
};
match spec.return_type {
crate::functions::ReturnType::Integer => InferredType::Data(DataType::Integer),
crate::functions::ReturnType::Decimal => InferredType::Data(DataType::Decimal),
crate::functions::ReturnType::Numeric => InferredType::Unknown,
crate::functions::ReturnType::Currency => InferredType::Data(DataType::Currency),
crate::functions::ReturnType::Boolean => InferredType::Data(DataType::Boolean),
crate::functions::ReturnType::DateTime => InferredType::Data(DataType::DateTime),
crate::functions::ReturnType::String => InferredType::Data(DataType::String),
crate::functions::ReturnType::Variant => InferredType::Data(DataType::Variant),
crate::functions::ReturnType::Table => InferredType::Table,
crate::functions::ReturnType::Blank => InferredType::Blank,
crate::functions::ReturnType::Any => InferredType::Unknown,
}
}
/// Infers the result type of a unary operator. `+` and `-` preserve the numeric type (DateTime
/// keeps its serial type); `NOT` always yields Boolean. A BLANK operand stays polymorphic
/// instead of becoming Integer.
pub fn unary_type(op: UnaryOp, operand: InferredType) -> Result<InferredType, TypeError> {
match op {
UnaryOp::Not => match operand {
InferredType::Table | InferredType::Data(DataType::Binary) => Err(TypeError::IncompatibleUnaryOperand { op, operand }),
_ => Ok(InferredType::Data(DataType::Boolean)),
},
UnaryOp::Plus | UnaryOp::Neg => match operand {
InferredType::Data(DataType::Integer) => Ok(InferredType::Data(DataType::Integer)),
InferredType::Data(DataType::Currency) => Ok(InferredType::Data(DataType::Currency)),
InferredType::Data(DataType::Decimal) => Ok(InferredType::Data(DataType::Decimal)),
// TRUE/FALSE are 1/0 when a numeric operator needs a number.
InferredType::Data(DataType::Boolean) => Ok(InferredType::Data(DataType::Integer)),
InferredType::Data(DataType::Variant) => Ok(InferredType::Data(DataType::Variant)),
// DAX documents unary `-` as preserving the operand type, and DateTime is a serial.
InferredType::Data(DataType::DateTime) => Ok(InferredType::Data(DataType::DateTime)),
// A text operand may parse as a number at runtime.
InferredType::Data(DataType::String) | InferredType::Unknown => Ok(InferredType::Unknown),
InferredType::Blank => Ok(InferredType::Blank),
InferredType::Data(DataType::Binary) | InferredType::Table => Err(TypeError::IncompatibleUnaryOperand { op, operand }),
},
}
}
/// Infers the result type of a binary operator using the documented DAX tables.
pub fn binary_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
match op {
BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow => arithmetic_type(op, left, right),
BinaryOp::Concat => {
reject_non_scalar(op, left, right)?;
Ok(InferredType::Data(DataType::String))
}
BinaryOp::And | BinaryOp::Or => {
reject_non_scalar(op, left, right)?;
Ok(InferredType::Data(DataType::Boolean))
}
BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => {
comparison_type(op, left, right).map(InferredType::Data)
}
BinaryOp::In => in_type(op, left, right),
}
}
/// `IN` always yields Boolean. Its right operand is a table expression (`{ ... }`, a table
/// reference or `VALUES(...)`), not a scalar.
fn in_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
if matches!(left, InferredType::Table | InferredType::Data(DataType::Binary)) {
return Err(TypeError::IncompatibleOperands { op, left, right });
}
match right {
InferredType::Table | InferredType::Unknown | InferredType::Data(DataType::Variant) => Ok(InferredType::Data(DataType::Boolean)),
InferredType::Data(_) | InferredType::Blank => Err(TypeError::IncompatibleOperands { op, left, right }),
}
}
/// Infers the result of `+`, `-`, `*`, `/` or `^`.
///
/// Unknown operands stay unknown. Text operands stay unknown because only the evaluator can
/// decide whether the text parses as a number. Variant propagates. BLANK is polymorphic and
/// follows the documented special cases instead of being treated as Integer.
pub fn arithmetic_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
if !matches!(op, BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow) {
return Err(TypeError::IncompatibleOperands { op, left, right });
}
reject_non_scalar(op, left, right)?;
if left == InferredType::Blank || right == InferredType::Blank {
return blank_arithmetic(op, left, right);
}
if matches!(left, InferredType::Data(DataType::Variant)) || matches!(right, InferredType::Data(DataType::Variant)) {
return Ok(InferredType::Data(DataType::Variant));
}
if left == InferredType::Unknown || right == InferredType::Unknown {
return Ok(InferredType::Unknown);
}
if matches!(left, InferredType::Data(DataType::String)) || matches!(right, InferredType::Data(DataType::String)) {
// `"22" + 22` succeeds only if the text parses; that is evaluator work.
return Ok(InferredType::Unknown);
}
let converted_left = coerce_boolean(left);
let converted_right = coerce_boolean(right);
let (Some(left_data), Some(right_data)) = (converted_left.data(), converted_right.data()) else {
return Err(TypeError::IncompatibleOperands { op, left, right });
};
let result = match op {
BinaryOp::Add => numeric_cell(&ADDITION, left_data, right_data),
BinaryOp::Sub => numeric_cell(&SUBTRACTION, left_data, right_data),
BinaryOp::Mul => multiplication_cell(left_data, right_data),
BinaryOp::Div => numeric_cell(&DIVISION, left_data, right_data),
BinaryOp::Pow => match (left_data, right_data) {
// `^` is not covered by the conversion tables; the engine computes a double.
(DataType::DateTime, _) | (_, DataType::DateTime) => None,
_ => Some(DataType::Decimal),
},
_ => None,
};
result.map(InferredType::Data).ok_or(TypeError::IncompatibleOperands { op, left, right })
}
/// BLANK arithmetic follows the documented special cases:
/// `BLANK()+5 = 5`, `BLANK()*5 = BLANK`, `5/BLANK() = Infinity` and
/// `BLANK()/BLANK() = BLANK`. The runtime values are evaluator work; only the result types are
/// recorded here.
fn blank_arithmetic(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
let left_blank = left == InferredType::Blank;
let right_blank = right == InferredType::Blank;
match op {
BinaryOp::Add | BinaryOp::Sub => {
if left_blank && right_blank {
Ok(InferredType::Blank)
} else {
let other = if left_blank { right } else { left };
Ok(neutral_arithmetic(other))
}
}
// BLANK is absorbing in multiplication.
BinaryOp::Mul => Ok(InferredType::Blank),
BinaryOp::Div => {
if left_blank {
if right_blank {
Ok(InferredType::Blank)
} else if right == InferredType::Unknown {
Ok(InferredType::Unknown)
} else {
Ok(InferredType::Blank)
}
} else if right_blank {
if left == InferredType::Unknown {
Ok(InferredType::Unknown)
} else {
// 5/BLANK() is Infinity and 0/BLANK() is NaN: both are Decimal.
Ok(InferredType::Data(DataType::Decimal))
}
} else {
Ok(InferredType::Unknown)
}
}
// The evaluator coerces a BLANK operand to 0 and answers a number, so exponentiation is
// Decimal rather than Blank.
BinaryOp::Pow => Ok(InferredType::Data(DataType::Decimal)),
_ => Err(TypeError::IncompatibleOperands { op, left, right }),
}
}
/// The result of `BLANK + x` / `BLANK - x`: BLANK is neutral, so `x`'s numeric type survives.
fn neutral_arithmetic(other: InferredType) -> InferredType {
match other {
InferredType::Data(DataType::Boolean) => InferredType::Data(DataType::Integer),
InferredType::Data(DataType::String) => InferredType::Unknown,
InferredType::Data(DataType::Variant) => InferredType::Data(DataType::Variant),
InferredType::Data(DataType::Binary) | InferredType::Table => InferredType::Unknown,
other => other,
}
}
const fn coerce_boolean(value: InferredType) -> InferredType {
match value {
InferredType::Data(DataType::Boolean) => InferredType::Data(DataType::Integer),
other => other,
}
}
/// Resolves the common type for a non-strict comparison (`=`, `<>`, `<`, `>`, `<=`, `>=`).
///
/// BLANK is coerced to the other operand's type (`0`, `""` or `FALSE` according to that type):
/// `BLANK() = 0` is TRUE. Text is never compared implicitly with a number or a Boolean; those
/// combinations are a [`TypeError`]. `==` does not use this function, because strict equality
/// does not coerce BLANK.
pub fn comparison_coercion(left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
if matches!(left, InferredType::Table | InferredType::Data(DataType::Binary))
|| matches!(right, InferredType::Table | InferredType::Data(DataType::Binary))
{
return Err(TypeError::IncompatibleTypes { left, right });
}
if left == InferredType::Blank && right == InferredType::Blank {
return Ok(InferredType::Blank);
}
if left == InferredType::Blank {
return Ok(right);
}
if right == InferredType::Blank {
return Ok(left);
}
match (left, right) {
(InferredType::Unknown, _) | (_, InferredType::Unknown) => Ok(InferredType::Unknown),
(InferredType::Data(DataType::Variant), _) | (_, InferredType::Data(DataType::Variant)) => Ok(InferredType::Data(DataType::Variant)),
(InferredType::Data(DataType::Boolean), InferredType::Data(DataType::Boolean)) => Ok(InferredType::Data(DataType::Boolean)),
(InferredType::Data(DataType::String), InferredType::Data(DataType::String)) => Ok(InferredType::Data(DataType::String)),
(InferredType::Data(left_data), InferredType::Data(right_data)) => {
numeric_cell(&COMPARISON, left_data, right_data).map(InferredType::Data).ok_or(TypeError::IncompatibleTypes { left, right })
}
(InferredType::Table, _) | (_, InferredType::Table) => Err(TypeError::IncompatibleTypes { left, right }),
// BLANK returns above; this arm keeps the match exhaustive without a panic.
(InferredType::Blank, _) | (_, InferredType::Blank) => Ok(InferredType::Blank),
}
}
/// Checks whether a comparison operator accepts the two operands.
///
/// Non-strict operators use [`comparison_coercion`]. `==` is strict: BLANK is never replaced
/// with `0`, `""` or FALSE, though a BLANK operand is still comparable. Numeric/DateTime
/// pairs keep the documented comparison matrix; String/Boolean pairs are same-type only.
pub fn comparison_compatible(op: BinaryOp, left: InferredType, right: InferredType) -> Result<(), TypeError> {
if !op.is_comparison() {
return Err(TypeError::IncompatibleOperands { op, left, right });
}
if matches!(left, InferredType::Table | InferredType::Data(DataType::Binary))
|| matches!(right, InferredType::Table | InferredType::Data(DataType::Binary))
{
return Err(TypeError::IncompatibleOperands { op, left, right });
}
if op == BinaryOp::StrictEq {
if left == InferredType::Blank || right == InferredType::Blank {
return Ok(());
}
let compatible = matches!(
(left, right),
(InferredType::Unknown, _)
| (_, InferredType::Unknown)
| (InferredType::Data(DataType::Variant), _)
| (_, InferredType::Data(DataType::Variant))
| (InferredType::Data(DataType::Boolean), InferredType::Data(DataType::Boolean))
| (InferredType::Data(DataType::String), InferredType::Data(DataType::String))
) || matches!(
(left.data(), right.data()),
(Some(left_data), Some(right_data))
if numeric_index(left_data).is_some() && numeric_index(right_data).is_some()
);
return if compatible { Ok(()) } else { Err(TypeError::IncompatibleOperands { op, left, right }) };
}
comparison_coercion(left, right).map(|_| ()).map_err(|_| TypeError::IncompatibleOperands { op, left, right })
}
/// The result of any comparison is Boolean. This also checks operand compatibility.
pub fn comparison_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<DataType, TypeError> {
comparison_compatible(op, left, right)?;
Ok(DataType::Boolean)
}
fn reject_non_scalar(op: BinaryOp, left: InferredType, right: InferredType) -> Result<(), TypeError> {
match (left, right) {
(InferredType::Table, _)
| (_, InferredType::Table)
| (InferredType::Data(DataType::Binary), _)
| (_, InferredType::Data(DataType::Binary)) => Err(TypeError::IncompatibleOperands { op, left, right }),
_ => Ok(()),
}
}
// Documented operator result tables (rows = left operand, columns = right operand) for
// Integer, Currency, Decimal ("Real") and DateTime. They are transcribed cell for cell.
const NUMERIC_ORDER: [DataType; 4] = [DataType::Integer, DataType::Currency, DataType::Decimal, DataType::DateTime];
const ADDITION: [[DataType; 4]; 4] = [
[DataType::Integer, DataType::Currency, DataType::Decimal, DataType::DateTime],
[DataType::Currency, DataType::Currency, DataType::Decimal, DataType::DateTime],
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::DateTime],
[DataType::DateTime, DataType::DateTime, DataType::DateTime, DataType::DateTime],
];
const SUBTRACTION: [[DataType; 4]; 4] = [
[DataType::Integer, DataType::Currency, DataType::Decimal, DataType::Decimal],
[DataType::Currency, DataType::Currency, DataType::Decimal, DataType::Decimal],
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
[DataType::DateTime, DataType::DateTime, DataType::DateTime, DataType::DateTime],
];
const MULTIPLICATION: [[Option<DataType>; 4]; 4] = [
[Some(DataType::Integer), Some(DataType::Currency), Some(DataType::Decimal), Some(DataType::Integer)],
[Some(DataType::Currency), Some(DataType::Decimal), Some(DataType::Currency), Some(DataType::Currency)],
[Some(DataType::Decimal), Some(DataType::Currency), Some(DataType::Decimal), Some(DataType::Decimal)],
[None, None, None, None],
];
const DIVISION: [[DataType; 4]; 4] = [
[DataType::Decimal, DataType::Currency, DataType::Decimal, DataType::Decimal],
[DataType::Currency, DataType::Decimal, DataType::Currency, DataType::Decimal],
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
];
const COMPARISON: [[DataType; 4]; 4] = [
[DataType::Integer, DataType::Currency, DataType::Decimal, DataType::Decimal],
[DataType::Currency, DataType::Currency, DataType::Decimal, DataType::Decimal],
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::DateTime],
];
const fn numeric_index(data_type: DataType) -> Option<usize> {
match data_type {
DataType::Integer => Some(0),
DataType::Currency => Some(1),
DataType::Decimal => Some(2),
DataType::DateTime => Some(3),
DataType::Binary | DataType::Boolean | DataType::String | DataType::Variant => None,
}
}
fn numeric_cell(matrix: &[[DataType; 4]; 4], left: DataType, right: DataType) -> Option<DataType> {
let row = numeric_index(left)?;
let column = numeric_index(right)?;
matrix.get(row)?.get(column).copied()
}
fn multiplication_cell(left: DataType, right: DataType) -> Option<DataType> {
let row = numeric_index(left)?;
let column = numeric_index(right)?;
MULTIPLICATION.get(row)?.get(column).copied().flatten()
}
/// The row/column order of the operator tables, exposed for tests and tooling that wants to
/// verify a particular documented cell.
pub const fn numeric_matrix_order() -> [DataType; 4] {
NUMERIC_ORDER
}
-187
View File
@@ -1,187 +0,0 @@
//! Static validation of catalogued function calls.
//!
//! The parser accepts any `NAME ( args )`; this module applies the catalog in
//! [`crate::functions`] to reject what can be decided without a data model, for every catalog
//! category:
//!
//! - argument counts against the documented arities (including `COUNTROWS ()` and the optional
//! `Variant` of `MAXX`/`MINX`);
//! - column-only parameters that are not a bracketed name reference (`SUM ( 1 )`);
//! - table parameters that are certainly not a table: an obvious scalar literal or scalar operator
//! expression (`COUNTROWS ( 1 )`) or a bracketed column reference (`COUNTROWS ( Sales[Amount] )`).
//! Dynamic table expressions such as `FILTER ( ... )`, `DISTINCT ( ... )`, variables and table
//! constructors are accepted.
//!
//! Unknown functions are ignored, so the validator can run over expressions that use the rest of
//! the DAX language.
use std::fmt;
use crate::ast::{Call, Expr, ExprKind, NameStyle, Span};
use crate::functions::{FunctionSpec, Overload, ParamKind, lookup};
/// The category of a validation failure.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ValidationErrorKind {
/// Wrong number of arguments for every documented overload.
Arity,
/// The argument at the reported span cannot satisfy the parameter kind.
ArgumentKind,
}
impl ValidationErrorKind {
pub const fn description(self) -> &'static str {
match self {
ValidationErrorKind::Arity => "wrong number of arguments",
ValidationErrorKind::ArgumentKind => "wrong argument kind",
}
}
}
/// One error found by [`validate_call`] or [`validate_expression`].
///
/// `function` is the catalog spelling, `span` is the offending argument for kind errors and the
/// whole call for arity errors. [`validate_call`] has no span for the call itself, so arity
/// errors it returns carry an empty span; [`validate_expression`] fills the expression span.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValidationError {
pub function: &'static str,
pub kind: ValidationErrorKind,
pub message: String,
pub span: Span,
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} at bytes {}..{}", self.message, self.span.start, self.span.end)
}
}
impl std::error::Error for ValidationError {}
/// Validates one call against the function catalog.
///
/// Returns every error the call contains, or an empty vector for a valid call and for a function
/// that is not in the catalog. Because [`Call`] does not carry its own span, arity errors use
/// [`Span::empty`]; use [`validate_expression`] when spans matter.
pub fn validate_call(call: &Call) -> Vec<ValidationError> {
validate_call_at(call, Span::empty())
}
/// Walks the expression tree and reports every invalid call to a known aggregation function.
///
/// Unknown functions are ignored but their arguments are still visited, so a bad `SUM` nested in
/// `CALCULATE (...)` is reported. Results are in depth-first source order.
pub fn validate_expression(expr: &Expr) -> Vec<ValidationError> {
let mut errors = Vec::new();
expr.walk(&mut |node| {
if let ExprKind::Call(call) = &node.kind {
errors.extend(validate_call_at(call, node.span));
}
});
errors
}
fn validate_call_at(call: &Call, call_span: Span) -> Vec<ValidationError> {
let Some(spec) = lookup(&call.name.text) else {
return Vec::new();
};
let arity = call.args.len();
if arity < spec.min_args || arity > spec.max_args {
return vec![arity_error(spec, arity, call_span)];
}
let matching: Vec<&Overload> = spec.overloads.iter().filter(|overload| overload.matches(arity)).collect();
if matching.is_empty() {
return vec![arity_error(spec, arity, call_span)];
}
let mut errors = Vec::new();
for (index, argument) in call.args.iter().enumerate() {
if matching.iter().any(|overload| overload_accepts(overload, index, argument)) {
continue;
}
let expected = expected_kinds(&matching, index);
errors.push(ValidationError {
function: spec.name,
kind: ValidationErrorKind::ArgumentKind,
message: format!("{} argument {} must be {expected}, found {}", spec.name, index + 1, describe_argument(argument)),
span: argument.span,
});
}
errors
}
fn arity_error(spec: &FunctionSpec, arity: usize, span: Span) -> ValidationError {
let expected = if spec.min_args == spec.max_args { format!("{}", spec.min_args) } else { format!("{} to {}", spec.min_args, spec.max_args) };
ValidationError {
function: spec.name,
kind: ValidationErrorKind::Arity,
message: format!("{} expects {expected} argument(s), found {arity}", spec.name),
span,
}
}
fn overload_accepts(overload: &Overload, index: usize, argument: &Expr) -> bool {
match overload.kind_at(index) {
Some(kind) => accepts(kind, argument),
None => true,
}
}
fn expected_kinds(overloads: &[&Overload], index: usize) -> String {
let mut expected: Vec<&'static str> = Vec::new();
for overload in overloads {
let Some(kind) = overload.kind_at(index) else {
continue;
};
let description = kind.description();
if !expected.contains(&description) {
expected.push(description);
}
}
expected.join(" or ")
}
/// The only argument checks that are decidable without a model.
fn accepts(kind: ParamKind, argument: &Expr) -> bool {
match kind {
ParamKind::Column => is_column_reference(argument),
ParamKind::Table => !is_obvious_scalar(argument) && !is_column_reference(argument),
ParamKind::Expression
| ParamKind::Scalar
| ParamKind::Logical
| ParamKind::Any
| ParamKind::Date
| ParamKind::Text
| ParamKind::Number
| ParamKind::Boolean
| ParamKind::Function
| ParamKind::Reference
| ParamKind::Json
| ParamKind::Variant => true,
}
}
fn is_column_reference(expr: &Expr) -> bool {
matches!(
&expr.kind,
ExprKind::Name(name_ref) if name_ref.name.style == NameStyle::Bracketed
)
}
/// Literals and operator expressions are certainly scalars, never tables. Names, calls, table
/// constructors and row constructors may be dynamic table expressions, so they are not rejected.
fn is_obvious_scalar(expr: &Expr) -> bool {
matches!(&expr.kind, ExprKind::Literal(_) | ExprKind::Unary { .. } | ExprKind::Binary { .. })
}
fn describe_argument(expr: &Expr) -> &'static str {
match &expr.kind {
ExprKind::Literal(_) => "a literal",
ExprKind::Name(_) => "a name reference",
ExprKind::Call(_) => "a function call",
ExprKind::Unary { .. } | ExprKind::Binary { .. } => "an operator expression",
ExprKind::Table(_) => "a table constructor",
ExprKind::Tuple(_) => "a row constructor",
ExprKind::VarReturn { .. } => "a VAR/RETURN expression",
}
}
-609
View File
@@ -1,609 +0,0 @@
//! Runtime values for the DAX evaluator.
//!
//! Scalar values cover the DAX scalar types; tables are column-oriented metadata plus rows of
//! scalars. BLANK is a distinct value, never silently zero or the empty string.
use std::cmp::Ordering;
use std::collections::BTreeSet;
use serde::{Deserialize, Serialize};
/// A DAX scalar value.
///
/// `Currency` and `DateTime` are plain numbers in DAX, so an untagged numeric representation
/// would read them back as `Integer`/`Decimal`. They serialize as tagged JSON objects instead:
/// `{"$currency": 1234}` (scaled by 10,000) and `{"$dateTime": 45292.5}`. Every other variant
/// keeps its natural JSON form, so existing model files and command output stay unchanged.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Scalar {
/// BLANK. It serializes as `null` and is the first untagged match.
Blank,
Boolean(bool),
Integer(i64),
/// Currency is an integer scaled by 10,000.
#[serde(with = "currency_serde")]
Currency(i64),
/// A decimal. A finite value is a JSON number; `NaN`/`Infinity` become `{"$decimal": "NaN"}`
/// so they survive a round trip (`serde_json` writes a non-finite float as `null`, which would
/// read back as BLANK).
#[serde(with = "decimal_serde")]
Decimal(f64),
/// DateTime is an OLE Automation serial: whole days since 1899-12-30 plus a time fraction.
#[serde(with = "datetime_serde")]
DateTime(f64),
String(String),
}
mod currency_serde {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Serialize, Deserialize)]
struct Tagged {
#[serde(rename = "$currency")]
value: i64,
}
pub fn serialize<S: Serializer>(value: &i64, serializer: S) -> Result<S::Ok, S::Error> {
Tagged { value: *value }.serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
Ok(Tagged::deserialize(deserializer)?.value)
}
}
mod decimals {
/// The JSON text of a non-finite value, or `None` when it is finite.
pub fn to_text(value: f64) -> Option<&'static str> {
if value.is_nan() {
Some("NaN")
} else if value == f64::INFINITY {
Some("Infinity")
} else if value == f64::NEG_INFINITY {
Some("-Infinity")
} else {
None
}
}
/// The value of a JSON text produced by [`to_text`].
pub fn from_text(text: &str) -> Option<f64> {
match text {
"NaN" => Some(f64::NAN),
"Infinity" => Some(f64::INFINITY),
"-Infinity" => Some(f64::NEG_INFINITY),
_ => None,
}
}
}
mod decimal_serde {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::decimals;
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum Json {
Number(f64),
Tagged {
#[serde(rename = "$decimal")]
text: String,
},
}
pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
match decimals::to_text(*value) {
Some(text) => Json::Tagged { text: text.to_string() }.serialize(serializer),
None => Json::Number(*value).serialize(serializer),
}
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
match Json::deserialize(deserializer)? {
Json::Number(value) => Ok(value),
Json::Tagged { text } => decimals::from_text(&text).ok_or_else(|| serde::de::Error::custom("unknown non-finite decimal")),
}
}
}
mod datetime_serde {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::decimals;
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum Number {
Finite(f64),
Text(String),
}
#[derive(Serialize, Deserialize)]
struct Tagged {
#[serde(rename = "$dateTime")]
value: Number,
}
pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
let value = match decimals::to_text(*value) {
Some(text) => Number::Text(text.to_string()),
None => Number::Finite(*value),
};
Tagged { value }.serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
match Tagged::deserialize(deserializer)?.value {
Number::Finite(value) => Ok(value),
Number::Text(text) => decimals::from_text(&text).ok_or_else(|| serde::de::Error::custom("unknown non-finite serial")),
}
}
}
impl Scalar {
pub fn is_blank(&self) -> bool {
matches!(self, Scalar::Blank)
}
pub fn type_name(&self) -> &'static str {
match self {
Scalar::Blank => "BLANK",
Scalar::Boolean(_) => "Boolean",
Scalar::Integer(_) => "Integer",
Scalar::Currency(_) => "Currency",
Scalar::Decimal(_) => "Decimal",
Scalar::DateTime(_) => "DateTime",
Scalar::String(_) => "String",
}
}
/// Whether the value is one of the four numeric variants, without coercing anything else.
pub fn is_numeric(&self) -> bool {
matches!(self, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_))
}
/// DAX arithmetic coercion: BLANK is 0, booleans are 1/0, numeric text parses, dates are
/// serials, and currency is divided by 10,000.
pub fn to_number(&self) -> Option<f64> {
match self {
Scalar::Blank => Some(0.0),
Scalar::Boolean(value) => Some(if *value { 1.0 } else { 0.0 }),
Scalar::Integer(value) => Some(*value as f64),
Scalar::Currency(value) => Some(*value as f64 / 10_000.0),
Scalar::Decimal(value) | Scalar::DateTime(value) => Some(*value),
// `f64::from_str` accepts "nan"/"inf"; DAX has no text form for those, so they are
// not numbers here.
Scalar::String(value) => value.trim().parse::<f64>().ok().filter(|number| number.is_finite()),
}
}
/// DAX's implicit text conversion, used by `&` and the text functions: a whole-valued number
/// prints without a decimal point (`10`, not `10.0`) and a date prints as its calendar text.
/// [`Scalar::to_text`] stays the storage/debug spelling other callers rely on.
pub fn to_dax_text(&self) -> String {
match self {
Scalar::Decimal(value) if value.is_finite() && value.fract() == 0.0 => {
// DAX switches to exponent form for very large whole numbers instead of printing
// every digit.
if value.abs() >= 1.0e15 {
// Excel writes the exponent's sign: `1E+15`, not Rust's `1E15`.
let text = format!("{value:E}");
match text.split_once('E') {
Some((mantissa, exponent)) if !exponent.starts_with('-') => format!("{mantissa}E+{exponent}"),
_ => text,
}
} else {
format!("{value:.0}")
}
}
Scalar::Currency(value) => {
// Integer arithmetic keeps every digit of the scaled range (about 19 significant
// digits); an f64 round trip would lose the low ones.
let sign = if *value < 0 { "-" } else { "" };
let magnitude = value.unsigned_abs();
let (whole, fraction) = (magnitude / 10_000, magnitude % 10_000);
if fraction == 0 { format!("{sign}{whole}") } else { format!("{sign}{whole}.{}", format!("{fraction:04}").trim_end_matches('0')) }
}
Scalar::DateTime(serial) => datetime_text(*serial),
// DAX prints at most 15 significant digits; Rust's shortest round-trip form can show
// 17 (`0.30000000000000004`), so fractional decimals are rounded first.
Scalar::Decimal(value) if value.is_finite() => {
let rounded: f64 = format!("{value:.14e}").parse().unwrap_or(*value);
rounded.to_string()
}
other => other.to_text(),
}
}
pub fn to_text(&self) -> String {
match self {
Scalar::Blank => String::new(),
Scalar::Boolean(true) => "TRUE".into(),
Scalar::Boolean(false) => "FALSE".into(),
Scalar::Integer(value) => value.to_string(),
Scalar::Currency(value) => format!("{:.4}", *value as f64 / 10_000.0),
Scalar::Decimal(value) => {
if value.fract() == 0.0 {
format!("{value:.1}")
} else {
value.to_string()
}
}
Scalar::DateTime(value) => value.to_string(),
Scalar::String(value) => value.clone(),
}
}
pub fn to_bool(&self) -> Option<bool> {
match self {
Scalar::Blank => Some(false),
Scalar::Boolean(value) => Some(*value),
Scalar::Integer(value) => Some(*value != 0),
Scalar::Currency(value) => Some(*value != 0),
Scalar::Decimal(value) => Some(*value != 0.0),
Scalar::DateTime(value) => Some(*value != 0.0),
Scalar::String(value) if value.eq_ignore_ascii_case("true") => Some(true),
Scalar::String(value) if value.eq_ignore_ascii_case("false") => Some(false),
Scalar::String(_) => None,
}
}
/// Comparison with DAX's blank coercion for `=`/ordering and case-insensitive strings.
///
/// `None` means the types are not comparable: text against a number or a logical, and any
/// pair with NaN. Text is never coerced to a number here — arithmetic coerces numeric text
/// (`to_number`), comparison does not — so the caller decides what an incomparable pair means
/// (the evaluator maps it to FALSE for `=`/ordering and to an error where DAX raises one).
pub fn compare(&self, other: &Scalar) -> Option<Ordering> {
match (self, other) {
(Scalar::Blank, Scalar::Blank) => Some(Ordering::Equal),
// BLANK converts to the empty string when compared with text, so `BLANK () = ""` is
// TRUE and `BLANK () <> ""` is FALSE, symmetrically.
(Scalar::Blank, Scalar::String(b)) => Some(String::new().cmp(&b.to_lowercase())),
(Scalar::String(a), Scalar::Blank) => Some(a.to_lowercase().cmp(&String::new())),
(Scalar::String(a), Scalar::String(b)) => Some(a.to_lowercase().cmp(&b.to_lowercase())),
(Scalar::String(_), _) | (_, Scalar::String(_)) => None,
(Scalar::Boolean(a), Scalar::Boolean(b)) => Some(a.cmp(b)),
// Two keys of the same integer variant compare exactly: above 2^53 the `f64` route
// would report distinct values as equal, and `IN`/`=` must not.
(Scalar::Integer(a), Scalar::Integer(b)) => Some(a.cmp(b)),
(Scalar::Currency(a), Scalar::Currency(b)) => Some(a.cmp(b)),
_ => numeric_compare(self, other),
}
}
/// Identity for relationship joins and member filters: BLANK equals only BLANK and text is
/// case-sensitive, while the numeric variants compare by value — a key can be `Integer` on one
/// side and `Decimal` or `Currency` on the other, and the two must still join.
pub fn strict_eq(&self, other: &Scalar) -> bool {
match (self, other) {
(Scalar::Blank, Scalar::Blank) => true,
(Scalar::String(a), Scalar::String(b)) => a == b,
(a, b) if a.is_numeric() && b.is_numeric() => {
// Two keys of the same variant compare exactly, however large they are.
if std::mem::discriminant(a) == std::mem::discriminant(b) {
return a == b;
}
match (exact_number(a), exact_number(b)) {
(Some(x), Some(y)) => x == y,
_ => false,
}
}
_ => self == other,
}
}
}
/// A comparable/hashable key used for filter context values, relationship joins and dictionary
/// lookups.
///
/// Keys keep the exact spelling: they double as the reported key in integrity findings. Where DAX
/// compares values for *distinctness* instead of identity — `DISTINCTCOUNT`, `VALUES`/`DISTINCT`
/// — the text folds through [`distinct_key`], which is the model's case-insensitive collation.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ScalarKey {
Blank,
Boolean(bool),
Integer(i64),
Currency(i64),
Decimal(u64),
DateTime(u64),
String(String),
}
impl From<&Scalar> for ScalarKey {
fn from(value: &Scalar) -> Self {
match value {
Scalar::Blank => ScalarKey::Blank,
Scalar::Boolean(value) => ScalarKey::Boolean(*value),
Scalar::Integer(value) => ScalarKey::Integer(*value),
Scalar::Currency(value) => ScalarKey::Currency(*value),
Scalar::Decimal(value) => ScalarKey::Decimal(order_bits(*value)),
Scalar::DateTime(value) => ScalarKey::DateTime(order_bits(*value)),
Scalar::String(value) => ScalarKey::String(value.clone()),
}
}
}
/// Compares two numeric scalars.
///
/// An `Integer` against a `Decimal`/`DateTime` is compared through `i128` when the decimal is
/// integral, so a value above 2^53 is not rounded into its neighbour; every other pair uses the
/// `f64` coercion DAX applies.
fn numeric_compare(left: &Scalar, right: &Scalar) -> Option<Ordering> {
fn exact(value: &Scalar) -> Option<i128> {
match value {
Scalar::Integer(number) => Some(i128::from(*number)),
Scalar::Decimal(number) | Scalar::DateTime(number) if number.fract() == 0.0 && number.abs() < 9.2e18 => Some(*number as i128),
_ => None,
}
}
let integer_involved = matches!(left, Scalar::Integer(_) | Scalar::Currency(_)) || matches!(right, Scalar::Integer(_) | Scalar::Currency(_));
if integer_involved && let (Some(a), Some(b)) = (exact(left), exact(right)) {
return Some(a.cmp(&b));
}
left.to_number()?.partial_cmp(&right.to_number()?)
}
/// [`relationship_key_of`] for a value: the key a relationship index stores for it under the
/// numeric rule.
pub(crate) fn relationship_key_of_value(value: &Scalar) -> ScalarKey {
relationship_key_of(&ScalarKey::from(value))
}
/// [`relationship_key`] for a key that is already normalized-except-for-variant.
pub(crate) fn relationship_key_of(key: &ScalarKey) -> ScalarKey {
match key {
ScalarKey::Integer(number) if number.unsigned_abs() <= (1 << 53) => ScalarKey::Decimal(order_bits(*number as f64)),
ScalarKey::Currency(number) if number.unsigned_abs() <= (1 << 53) => {
let major = *number as f64 / 10_000.0;
// The division must land back on the stored amount. Past roughly 2^49 hundredths it
// rounds, and two distinct currencies would then share one key.
if (major * 10_000.0).round() as i64 == *number { ScalarKey::Decimal(order_bits(major)) } else { key.clone() }
}
// A NaN serial has no ordering and never joins, so it keeps its own variant instead of
// folding onto a `Decimal` NaN with the same bits.
ScalarKey::DateTime(serial) if !bits_order(*serial).is_nan() => ScalarKey::Decimal(*serial),
other => other.clone(),
}
}
/// Intersects two key sets under [`folded_key`], keeping the left-hand representatives.
///
/// Two filters that allow `"East"` and `"east"` accept the same rows, so their intersection must
/// not be empty; the same holds for `Integer(2)` and `Decimal(2.0)`.
pub(crate) fn fold_intersect(left: &BTreeSet<ScalarKey>, right: &BTreeSet<ScalarKey>) -> BTreeSet<ScalarKey> {
let right: BTreeSet<ScalarKey> = right.iter().map(folded_key).collect();
left.iter().filter(|key| right.contains(&folded_key(key))).cloned().collect()
}
/// Whether a key holds a NaN value, which never joins and is never a relationship key.
pub(crate) fn is_nan_key(key: &ScalarKey) -> bool {
match key {
ScalarKey::Decimal(bits) | ScalarKey::DateTime(bits) => bits_order(*bits).is_nan(),
_ => false,
}
}
/// The same key with text folded to lower case: the rule filter keys and the values they are
/// compared with share, so a filter set from `VALUES` matches every spelling of the value.
pub(crate) fn folded_key(key: &ScalarKey) -> ScalarKey {
match key {
ScalarKey::String(text) => ScalarKey::String(text.to_lowercase()),
// Numbers fold to one variant too, so a filter key built from `Integer(3)` matches a
// column cell stored as `Decimal(3.0)` (a promoted column) and vice versa.
other => relationship_key_of(other),
}
}
/// The key a distinctness comparison uses: text folds to lower case, the model collation, so `"A"`
/// and `"a"` are one value. Every other type keeps its exact key.
///
/// `DISTINCTCOUNT`, `DISTINCTCOUNTNOBLANK`, `VALUES`/`DISTINCT` and the storage dictionary all use
/// this, so a faithful model and a row-scanned one count the same values.
pub(crate) fn distinct_key(value: &Scalar) -> ScalarKey {
// Text folds by case and numbers fold by value: a promoted column can hold `Integer(2)` and
// `Decimal(2.0)` in the same cell family, and DAX counts that as one value. The relationship
// rule keeps the conversions exact (and NaN distinct).
folded_key(&ScalarKey::from(value))
}
/// The numeric value of a variant that an `f64` holds exactly.
///
/// `Integer` and `Currency` are compared through their exact representation only up to 2^53:
/// beyond it `9007199254740992` and `9007199254740993` share an `f64`, and a relationship must not
/// treat two distinct keys as the same one.
fn exact_number(value: &Scalar) -> Option<f64> {
const LIMIT: i64 = 1 << 53;
match value {
Scalar::Integer(number) if number.unsigned_abs() <= LIMIT as u64 => Some(*number as f64),
Scalar::Currency(number) if number.unsigned_abs() <= LIMIT as u64 => {
let major = *number as f64 / 10_000.0;
// The same round-trip rule the relationship key uses, so `strict_eq` and the join
// indexes cannot disagree about an amount that does not survive the division.
if (major * 10_000.0).round() as i64 == *number { Some(major) } else { None }
}
Scalar::Decimal(number) | Scalar::DateTime(number) => Some(*number),
_ => None,
}
}
/// Maps an `f64` to a `u64` whose unsigned order matches numeric order. `-0.0` and `0.0` map to
/// the same key, so `Ord` on [`ScalarKey`] sorts pivot groups numerically.
fn order_bits(value: f64) -> u64 {
let value = if value == 0.0 { 0.0 } else { value };
let bits = value.to_bits();
if bits >> 63 == 1 { !bits } else { bits | (1 << 63) }
}
/// Inverse of [`order_bits`].
pub(crate) fn bits_order(bits: u64) -> f64 {
let bits = if bits >> 63 == 1 { bits & !(1 << 63) } else { !bits };
f64::from_bits(bits)
}
impl ScalarKey {
/// Rebuilds the scalar that produced this key.
pub fn to_scalar(&self) -> Scalar {
match self {
ScalarKey::Blank => Scalar::Blank,
ScalarKey::Boolean(value) => Scalar::Boolean(*value),
ScalarKey::Integer(value) => Scalar::Integer(*value),
ScalarKey::Currency(value) => Scalar::Currency(*value),
ScalarKey::Decimal(value) => Scalar::Decimal(bits_order(*value)),
ScalarKey::DateTime(value) => Scalar::DateTime(bits_order(*value)),
ScalarKey::String(value) => Scalar::String(value.clone()),
}
}
}
/// A `DateTime` serial as DAX prints it: `M/D/YYYY H:MM:SS AM/PM`.
fn datetime_text(serial: f64) -> String {
use chrono::Datelike;
// A non-finite serial is not a date: print the value itself instead of a fabricated one
// (`NaN.floor() as i64` is 0, which would render as 1899-12-30 noon).
if !serial.is_finite() {
return serial.to_string();
}
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30);
let Some(epoch) = epoch else { return serial.to_string() };
let mut seconds = ((serial - serial.floor()) * 86_400.0).round() as i64;
let mut days = serial.floor() as i64;
if seconds >= 86_400 {
seconds -= 86_400;
days = days.saturating_add(1);
}
let Some(date) = chrono::Duration::try_days(days).and_then(|offset| epoch.checked_add_signed(offset)) else {
return serial.to_string();
};
let (hour, minute, second) = (seconds / 3600, (seconds / 60) % 60, seconds % 60);
let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
let meridiem = if hour < 12 { "AM" } else { "PM" };
format!("{}/{}/{} {}:{minute:02}:{second:02} {meridiem}", date.month(), date.day(), date.year(), hour12)
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TableColumn {
pub name: String,
}
/// A materialized table value.
#[derive(Clone, Debug, PartialEq)]
pub struct TableValue {
pub columns: Vec<TableColumn>,
pub rows: Vec<Vec<Scalar>>,
/// The model table this value came from, when known. It lets row-context evaluation avoid
/// guessing from column names.
pub lineage: Option<usize>,
}
impl TableValue {
pub fn new(columns: Vec<TableColumn>, rows: Vec<Vec<Scalar>>) -> Self {
TableValue { columns, rows, lineage: None }
}
pub fn with_lineage(mut self, lineage: usize) -> Self {
self.lineage = Some(lineage);
self
}
/// Keeps the existing lineage when the input had one.
pub fn with_lineage_if(mut self, lineage: Option<usize>) -> Self {
self.lineage = lineage;
self
}
/// Builds a table from rows whose column names are given.
pub fn from_rows(columns: Vec<TableColumn>, rows: Vec<Vec<Scalar>>, lineage: Option<usize>) -> Self {
TableValue { columns, rows, lineage }
}
pub fn column_index(&self, name: &str) -> Option<usize> {
self.columns.iter().position(|column| column.name.eq_ignore_ascii_case(name))
}
pub fn column(&self, index: usize) -> Vec<Scalar> {
self.rows.iter().filter_map(|row| row.get(index).cloned()).collect()
}
pub fn distinct_rows(&self) -> Self {
let mut seen = BTreeSet::new();
let mut rows = Vec::new();
for row in &self.rows {
let key: Vec<ScalarKey> = row.iter().map(distinct_key).collect();
if seen.insert(key) {
rows.push(row.clone());
}
}
TableValue { columns: self.columns.clone(), rows, lineage: self.lineage }
}
}
/// A runtime evaluation error.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("{message}")]
pub struct EvalError {
pub message: String,
}
impl EvalError {
pub fn new(message: impl Into<String>) -> Self {
EvalError { message: message.into() }
}
pub fn not_implemented(name: &str) -> Self {
EvalError::new(format!("DAX function `{name}` is not implemented by this evaluator"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn distinct_keys_treat_one_number_as_one_value() {
assert_eq!(distinct_key(&Scalar::Integer(2)), distinct_key(&Scalar::Decimal(2.0)));
assert_eq!(distinct_key(&Scalar::Currency(20_000)), distinct_key(&Scalar::Decimal(2.0)));
assert_eq!(distinct_key(&Scalar::String("A".into())), distinct_key(&Scalar::String("a".into())));
assert_ne!(distinct_key(&Scalar::Integer(2)), distinct_key(&Scalar::Integer(3)));
// A non-finite serial prints as itself, not as a fabricated calendar date.
assert_eq!(Scalar::DateTime(f64::NAN).to_dax_text(), "NaN");
}
#[test]
fn non_finite_values_survive_a_json_round_trip() {
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
for scalar in [Scalar::Decimal(value), Scalar::DateTime(value)] {
let json = serde_json::to_value(&scalar).expect("serialize");
let back: Scalar = serde_json::from_value(json.clone()).expect("deserialize");
assert_eq!(format!("{back:?}"), format!("{scalar:?}"), "round trip through {json}");
}
}
// A finite decimal keeps its natural JSON number, and text is still text.
assert_eq!(serde_json::to_value(Scalar::Decimal(1.5)).expect("serialize"), serde_json::json!(1.5));
let text: Scalar = serde_json::from_value(serde_json::json!("NaN")).expect("deserialize");
assert_eq!(text, Scalar::String("NaN".into()));
}
#[test]
fn relationship_keys_normalize_only_what_is_exact() {
// Integer and currency amounts fold onto the decimal key a decimal column uses.
assert_eq!(relationship_key_of(&ScalarKey::Integer(2)), relationship_key_of(&ScalarKey::Decimal(order_bits(2.0))));
assert_eq!(relationship_key_of(&ScalarKey::Currency(20_000)), relationship_key_of(&ScalarKey::Decimal(order_bits(2.0))));
// A currency amount whose major-unit division cannot round-trip keeps its own key.
let huge = 5_500_000_000_000_001_i64;
assert_ne!(
relationship_key_of(&ScalarKey::Currency(huge)),
relationship_key_of(&ScalarKey::Currency(huge + 1)),
"two distinct currency keys must not collapse"
);
// A NaN serial never joins, so it keeps its variant instead of matching a decimal NaN.
assert_ne!(
relationship_key_of(&ScalarKey::from(&Scalar::DateTime(f64::NAN))),
relationship_key_of(&ScalarKey::from(&Scalar::Decimal(f64::NAN))),
);
}
}
-526
View File
@@ -1,526 +0,0 @@
//! Integration tests for the aggregation catalog and its static validation.
use gridcraft_dax::functions::{BlankPolicy, FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog, lookup};
use gridcraft_dax::{Expr, ExprKind, ValidationError, ValidationErrorKind, parse_expression, validate_call, validate_expression};
fn aggregation_catalog() -> Vec<&'static FunctionSpec> {
catalog().iter().filter(|spec| spec.category == FunctionCategory::Aggregation).collect()
}
const FUNCTIONS: [(&str, usize, usize); 22] = [
("APPROXIMATEDISTINCTCOUNT", 1, 1),
("AVERAGE", 1, 1),
("AVERAGEA", 1, 1),
("AVERAGEX", 2, 2),
("COUNT", 1, 1),
("COUNTA", 1, 1),
("COUNTAX", 2, 2),
("COUNTBLANK", 1, 1),
("COUNTROWS", 0, 1),
("COUNTX", 2, 2),
("DISTINCTCOUNT", 1, 1),
("DISTINCTCOUNTNOBLANK", 1, 1),
("MAX", 1, 2),
("MAXA", 1, 1),
("MAXX", 2, 3),
("MIN", 1, 2),
("MINA", 1, 1),
("MINX", 2, 3),
("PRODUCT", 1, 1),
("PRODUCTX", 2, 2),
("SUM", 1, 1),
("SUMX", 2, 2),
];
fn parse(src: &str) -> Expr {
match parse_expression(src) {
Ok(expr) => expr,
Err(error) => panic!("{src:?} did not parse: {error}"),
}
}
fn spec(name: &str) -> &'static FunctionSpec {
match lookup(name) {
Some(spec) => spec,
None => panic!("{name} is missing from the catalog"),
}
}
fn expression_errors(src: &str) -> Vec<ValidationError> {
validate_expression(&parse(src))
}
fn call_errors(src: &str) -> Vec<ValidationError> {
let expr = parse(src);
match &expr.kind {
ExprKind::Call(call) => validate_call(call),
other => panic!("{src:?} is not a call: {other:?}"),
}
}
fn assert_valid(src: &str) {
let errors = expression_errors(src);
assert!(errors.is_empty(), "{src:?} should validate, got {errors:?}");
}
fn assert_invalid_kind(src: &str, kind: ValidationErrorKind) -> Vec<ValidationError> {
let errors = expression_errors(src);
assert!(!errors.is_empty(), "{src:?} should be rejected");
assert!(errors.iter().any(|error| error.kind == kind), "{src:?} should report {kind:?}, got {errors:?}");
errors
}
fn overload_kinds(spec: &FunctionSpec, arity: usize) -> Option<Vec<ParamKind>> {
spec.overload_for(arity).map(|overload| overload.params.to_vec())
}
#[test]
fn catalog_has_every_aggregation_function_exactly_once_with_documented_arity() {
let specs = aggregation_catalog();
assert_eq!(specs.len(), FUNCTIONS.len());
for (name, min_args, max_args) in FUNCTIONS {
let matches: Vec<&FunctionSpec> = specs.iter().copied().filter(|spec| spec.name == name).collect();
assert_eq!(matches.len(), 1, "{name} should appear exactly once");
assert_eq!(matches[0].min_args, min_args, "{name} min arity");
assert_eq!(matches[0].max_args, max_args, "{name} max arity");
assert_eq!(matches[0].category, FunctionCategory::Aggregation);
}
let catalogued: std::collections::BTreeSet<&str> = specs.iter().map(|spec| spec.name).collect();
let documented: std::collections::BTreeSet<&str> = FUNCTIONS.iter().map(|(name, _, _)| *name).collect();
assert_eq!(catalogued, documented);
}
#[test]
fn lookup_is_case_insensitive() {
for (name, _, _) in FUNCTIONS {
assert_eq!(lookup(name).map(|spec| spec.name), Some(name));
assert_eq!(lookup(&name.to_ascii_lowercase()).map(|spec| spec.name), Some(name));
assert_eq!(lookup(&name.to_ascii_uppercase()).map(|spec| spec.name), Some(name));
}
assert_eq!(lookup("SuM").map(|spec| spec.name), Some("SUM"));
assert!(lookup("SUMM").is_none());
assert!(lookup("").is_none());
assert!(lookup("SUM ").is_none());
}
#[test]
fn every_record_has_consistent_signature_and_metadata() {
for spec in aggregation_catalog() {
assert!(!spec.description.is_empty(), "{} description", spec.name);
assert!(!spec.examples.is_empty(), "{} examples", spec.name);
assert_eq!(spec.params.len(), spec.max_args, "{} descriptive params", spec.name);
let required = spec.params.iter().filter(|param| !param.optional).count();
let optional = spec.params.iter().filter(|param| param.optional).count();
assert_eq!(required, spec.min_args, "{} required params", spec.name);
assert_eq!(optional, spec.max_args - spec.min_args, "{} optional params", spec.name);
assert!(!spec.overloads.is_empty(), "{} overloads", spec.name);
for arity in spec.min_args..=spec.max_args {
assert!(spec.overload_for(arity).is_some(), "{} has no overload for arity {arity}", spec.name);
}
let arities: Vec<usize> = spec.overloads.iter().map(|overload| overload.arity()).collect();
assert_eq!(arities.iter().min().copied(), Some(spec.min_args), "{} overload min", spec.name);
assert_eq!(arities.iter().max().copied(), Some(spec.max_args), "{} overload max", spec.name);
if let Some(target) = spec.sugar_of {
assert_ne!(target, spec.name, "{} is sugar of itself", spec.name);
assert!(lookup(target).is_some(), "{} sugar target {target} is missing", spec.name);
}
}
}
#[test]
fn iterator_and_sugar_metadata() {
let iterators = ["AVERAGEX", "COUNTAX", "COUNTX", "MAXX", "MINX", "PRODUCTX", "SUMX"];
for spec in aggregation_catalog() {
assert_eq!(spec.flags.iterator, iterators.contains(&spec.name), "{} iterator flag", spec.name);
assert_eq!(spec.is_iterator(), spec.flags.iterator, "{} is_iterator", spec.name);
}
for (name, target) in [("AVERAGE", "AVERAGEX"), ("COUNT", "COUNTX"), ("COUNTA", "COUNTAX"), ("PRODUCT", "PRODUCTX"), ("SUM", "SUMX")] {
assert_eq!(spec(name).sugar_of, Some(target), "{name} sugar");
}
for name in [
"APPROXIMATEDISTINCTCOUNT",
"DISTINCTCOUNTNOBLANK",
"MAX",
"MIN",
"AVERAGEA",
"AVERAGEX",
"COUNTAX",
"COUNTBLANK",
"COUNTROWS",
"COUNTX",
"DISTINCTCOUNT",
"MAXA",
"MAXX",
"MINA",
"MINX",
"PRODUCTX",
"SUMX",
] {
assert_eq!(spec(name).sugar_of, None, "{name} is not pure sugar");
}
}
#[test]
fn blank_policy_metadata() {
for (name, policy) in [
("APPROXIMATEDISTINCTCOUNT", BlankPolicy::BlankWhenEmpty),
("AVERAGE", BlankPolicy::Unspecified),
("AVERAGEA", BlankPolicy::Unspecified),
("AVERAGEX", BlankPolicy::BlankWhenEmpty),
("COUNT", BlankPolicy::BlankWhenEmpty),
("COUNTA", BlankPolicy::BlankWhenEmpty),
("COUNTAX", BlankPolicy::BlankWhenEmpty),
("COUNTBLANK", BlankPolicy::Unspecified),
("COUNTROWS", BlankPolicy::BlankWhenEmpty),
("COUNTX", BlankPolicy::BlankWhenEmpty),
("DISTINCTCOUNT", BlankPolicy::BlankWhenEmpty),
("DISTINCTCOUNTNOBLANK", BlankPolicy::Unspecified),
("MAX", BlankPolicy::Unspecified),
("MAXA", BlankPolicy::Unspecified),
("MAXX", BlankPolicy::Unspecified),
("MIN", BlankPolicy::Unspecified),
("MINA", BlankPolicy::Unspecified),
("MINX", BlankPolicy::Unspecified),
("PRODUCT", BlankPolicy::BlankWhenEmpty),
("PRODUCTX", BlankPolicy::BlankWhenEmpty),
("SUM", BlankPolicy::BlankWhenEmpty),
("SUMX", BlankPolicy::BlankWhenEmpty),
] {
assert_eq!(spec(name).blank_policy, policy, "{name} blank policy");
}
}
#[test]
fn return_type_metadata() {
for (name, return_type) in [
("APPROXIMATEDISTINCTCOUNT", ReturnType::Integer),
("AVERAGE", ReturnType::Numeric),
("AVERAGEA", ReturnType::Numeric),
("AVERAGEX", ReturnType::Numeric),
("COUNT", ReturnType::Integer),
("COUNTA", ReturnType::Integer),
("COUNTAX", ReturnType::Integer),
("COUNTBLANK", ReturnType::Integer),
("COUNTROWS", ReturnType::Integer),
("COUNTX", ReturnType::Integer),
("DISTINCTCOUNT", ReturnType::Integer),
("DISTINCTCOUNTNOBLANK", ReturnType::Integer),
("MAX", ReturnType::Any),
("MAXA", ReturnType::Any),
("MAXX", ReturnType::Any),
("MIN", ReturnType::Any),
("MINA", ReturnType::Any),
("MINX", ReturnType::Any),
("PRODUCT", ReturnType::Decimal),
("PRODUCTX", ReturnType::Decimal),
("SUM", ReturnType::Numeric),
("SUMX", ReturnType::Numeric),
] {
assert_eq!(spec(name).return_type, return_type, "{name} return type");
}
}
#[test]
fn compatibility_flags_are_honest() {
assert!(!spec("APPROXIMATEDISTINCTCOUNT").flags.excel_compatible);
assert!(!spec("DISTINCTCOUNTNOBLANK").flags.excel_compatible);
assert!(spec("COUNTROWS").flags.excel_compatible);
for spec in aggregation_catalog() {
if spec.name != "APPROXIMATEDISTINCTCOUNT" && spec.name != "DISTINCTCOUNTNOBLANK" {
assert!(spec.flags.excel_compatible, "{} should be Excel compatible", spec.name);
}
assert!(spec.flags.direct_query_limited, "{} DirectQuery note", spec.name);
}
let not_recommended: Vec<&str> = aggregation_catalog().iter().filter(|spec| spec.flags.not_recommended).map(|spec| spec.name).collect();
assert_eq!(not_recommended, ["AVERAGEA"]);
// COUNTROWS () is in the catalog even though Excel's embedded engine rejects that form.
assert_valid("COUNTROWS ( )");
assert_eq!(spec("COUNTROWS").min_args, 0);
}
#[test]
fn overloads_model_the_documented_signatures() {
assert_eq!(overload_kinds(spec("MAX"), 1), Some(vec![ParamKind::Column]));
assert_eq!(overload_kinds(spec("MAX"), 2), Some(vec![ParamKind::Scalar, ParamKind::Scalar]));
assert_eq!(overload_kinds(spec("MIN"), 1), Some(vec![ParamKind::Column]));
assert_eq!(overload_kinds(spec("MIN"), 2), Some(vec![ParamKind::Scalar, ParamKind::Scalar]));
assert_eq!(overload_kinds(spec("COUNTROWS"), 0), Some(Vec::new()));
assert_eq!(overload_kinds(spec("COUNTROWS"), 1), Some(vec![ParamKind::Table]));
assert_eq!(overload_kinds(spec("MAXX"), 2), Some(vec![ParamKind::Table, ParamKind::Expression]));
assert_eq!(overload_kinds(spec("MAXX"), 3), Some(vec![ParamKind::Table, ParamKind::Expression, ParamKind::Logical]));
assert_eq!(overload_kinds(spec("MINX"), 3), Some(vec![ParamKind::Table, ParamKind::Expression, ParamKind::Logical]));
let maxx = spec("MAXX");
assert_eq!(maxx.params.len(), 3);
assert_eq!(maxx.params[2].name, "Variant");
assert_eq!(maxx.params[2].kind, ParamKind::Logical);
assert!(maxx.params[2].optional);
}
#[test]
fn arity_boundaries_accept_and_reject_the_right_calls() {
for src in [
"SUM ( Sales[Amount] )",
"COUNTROWS ( )",
"COUNTROWS ( Sales )",
"MAX ( 1, 2 )",
"MAX ( Sales[Amount] )",
"MIN ( 3, 5 )",
"MAXX ( Sales, Sales[Amount] )",
"MAXX ( Sales, Sales[Amount], TRUE )",
"MINX ( Sales, Sales[Amount] )",
"MINX ( Sales, Sales[Amount], FALSE )",
"AVERAGEX ( Sales, Sales[Amount] )",
"COUNTAX ( Sales, Sales[Flag] )",
"COUNTX ( Sales, Sales[Quantity] )",
"PRODUCTX ( Sales, Sales[Quantity] )",
"SUMX ( Sales, Sales[Amount] )",
"DISTINCTCOUNT ( Sales[Region] )",
] {
assert_valid(src);
}
for src in [
"SUM ( )",
"SUM ( Sales[Amount], Sales[Amount] )",
"COUNTROWS ( Sales, Sales )",
"MAX ( )",
"MAX ( 1, 2, 3 )",
"MIN ( 1, 2, 3 )",
"MAXX ( Sales )",
"MAXX ( Sales, Sales[Amount], TRUE, FALSE )",
"MINX ( Sales )",
"MINX ( Sales, Sales[Amount], TRUE, FALSE )",
"AVERAGEX ( Sales )",
"AVERAGEX ( Sales, Sales[Amount], TRUE )",
"COUNTAX ( Sales )",
"COUNTX ( Sales )",
"PRODUCTX ( Sales )",
"SUMX ( Sales )",
"DISTINCTCOUNT ( )",
"COUNT ( )",
] {
let errors = assert_invalid_kind(src, ValidationErrorKind::Arity);
assert_eq!(errors.len(), 1, "{src:?} should report exactly one arity error: {errors:?}");
}
}
#[test]
fn every_documented_arity_boundary_is_enforced() {
for spec in aggregation_catalog() {
for arity in 0..=4usize {
let arguments = vec!["1"; arity].join(", ");
let src = format!("{} ( {arguments} )", spec.name);
let errors = expression_errors(&src);
let arity_errors: Vec<&ValidationError> = errors.iter().filter(|error| error.kind == ValidationErrorKind::Arity).collect();
if arity < spec.min_args || arity > spec.max_args {
assert_eq!(arity_errors.len(), 1, "{src:?} should report one arity error: {errors:?}");
} else {
assert!(arity_errors.is_empty(), "{src:?} has a documented overload and must not report an arity error: {errors:?}");
}
}
}
}
#[test]
fn column_only_arguments_must_be_bracketed_references() {
for src in [
"SUM ( 1 )",
"AVERAGE ( 1 + 1 )",
"COUNT ( \"x\" )",
"COUNTA ( TRUE )",
"COUNTBLANK ( 1 )",
"DISTINCTCOUNT ( 1 )",
"DISTINCTCOUNTNOBLANK ( 1 )",
"APPROXIMATEDISTINCTCOUNT ( 1 )",
"PRODUCT ( 1 )",
"MAXA ( 1 )",
"MINA ( 1 )",
"MAX ( 1 )",
"MIN ( 1 )",
"SUM ( -1 )",
] {
assert_invalid_kind(src, ValidationErrorKind::ArgumentKind);
}
for src in [
"SUM ( Sales[Amount] )",
"SUM ( [Amount] )",
"AVERAGE ( 'Sales'[Amount] )",
"COUNT ( Sales[Text] )",
"DISTINCTCOUNT ( Sales[Region] )",
"APPROXIMATEDISTINCTCOUNT ( Sales[ProductKey] )",
"PRODUCT ( Sales[Quantity] )",
"MAX ( Sales[Amount] )",
"MIN ( Sales[Amount] )",
"MAXA ( Sales[Flag] )",
"MINA ( Sales[Flag] )",
] {
assert_valid(src);
}
let errors = assert_invalid_kind("SUM ( 1 )", ValidationErrorKind::ArgumentKind);
let message = &errors[0].message;
assert!(message.contains("SUM"), "{message}");
assert!(message.contains("column reference"), "{message}");
assert!(message.contains("literal"), "{message}");
}
#[test]
fn table_arguments_reject_obvious_scalars_but_accept_dynamic_tables() {
for src in [
"COUNTROWS ( 1 )",
"COUNTROWS ( \"Sales\" )",
"COUNTROWS ( -1 )",
"COUNTROWS ( 1 + 1 )",
"COUNTROWS ( Sales[Amount] )",
"SUMX ( 1, Sales[Amount] )",
"AVERAGEX ( 1 + 1, Sales[Amount] )",
"MAXX ( TRUE, Sales[Amount] )",
"MINX ( 2 * 2, Sales[Amount] )",
"COUNTAX ( \"x\", Sales[Flag] )",
"COUNTX ( FALSE, Sales[Quantity] )",
] {
assert_invalid_kind(src, ValidationErrorKind::ArgumentKind);
}
for src in [
"COUNTROWS ( Sales )",
"COUNTROWS ( DISTINCT ( Sales[Region] ) )",
"COUNTROWS ( VALUES ( Sales[Region] ) )",
"COUNTROWS ( FILTER ( Sales, Sales[Amount] > 0 ) )",
"COUNTROWS ( { 1, 2 } )",
"SUMX ( FILTER ( Sales, Sales[Amount] > 0 ), Sales[Amount] )",
"SUMX ( { 1, 2, 3 }, [Value] )",
"AVERAGEX ( ALL ( Sales ), [Amount] )",
"MAXX ( Sales, Sales[Amount] )",
"MINX ( RELATEDTABLE ( ResellerSales ), [Sales Amount] )",
] {
assert_valid(src);
}
}
#[test]
fn max_and_min_model_both_overloads() {
assert_valid("MAX ( 1, 2 )");
assert_valid("MAX ( 3, 5 )");
assert_valid("MAX ( Sales[Amount] )");
assert_valid("MAX ( 10000, [Sales Amount] )");
assert_valid("MIN ( 3, 5 )");
assert_valid("MIN ( Sales[Net Price] )");
assert_valid("MIN ( 5000000, [Sales Amount] )");
// One argument is the column-only overload, not a scalar.
assert_invalid_kind("MAX ( 1 )", ValidationErrorKind::ArgumentKind);
assert_invalid_kind("MIN ( 1 )", ValidationErrorKind::ArgumentKind);
// Three arguments match no overload.
assert_invalid_kind("MAX ( 1, 2, 3 )", ValidationErrorKind::Arity);
assert_invalid_kind("MIN ( 1, 2, 3 )", ValidationErrorKind::Arity);
}
#[test]
fn countrows_accepts_zero_or_one_table_argument() {
for src in ["COUNTROWS ( )", "COUNTROWS ( Sales )", "COUNTROWS ( DISTINCT ( Sales[Region] ) )"] {
assert_valid(src);
}
assert_invalid_kind("COUNTROWS ( Sales, Sales )", ValidationErrorKind::Arity);
assert_invalid_kind("COUNTROWS ( 1 )", ValidationErrorKind::ArgumentKind);
let spec = spec("COUNTROWS");
assert_eq!((spec.min_args, spec.max_args), (0, 1));
assert_eq!(overload_kinds(spec, 0), Some(Vec::new()));
assert_eq!(overload_kinds(spec, 1), Some(vec![ParamKind::Table]));
}
#[test]
fn maxx_and_minx_accept_the_optional_variant_argument() {
for src in [
"MAXX ( Sales, Sales[Amount] )",
"MAXX ( Sales, Sales[Amount], TRUE )",
"MAXX ( Customer, 1 * Customer[LargeFamily] )",
"MINX ( Sales, Sales[Amount] )",
"MINX ( Sales, Sales[Amount], FALSE )",
"MINX ( Customer, 1 * Customer[NoCars] )",
] {
assert_valid(src);
}
assert_invalid_kind("MAXX ( Sales )", ValidationErrorKind::Arity);
assert_invalid_kind("MAXX ( Sales, Sales[Amount], TRUE, FALSE )", ValidationErrorKind::Arity);
assert_invalid_kind("MINX ( Sales )", ValidationErrorKind::Arity);
assert_invalid_kind("MINX ( Sales, Sales[Amount], TRUE, FALSE )", ValidationErrorKind::Arity);
}
#[test]
fn every_catalog_example_parses_and_validates() {
for spec in aggregation_catalog() {
assert!(!spec.examples.is_empty(), "{} has no examples", spec.name);
for example in spec.examples {
let expr = parse(example);
let errors = validate_expression(&expr);
assert!(errors.is_empty(), "{} example {example:?} should validate, got {errors:?}", spec.name);
}
}
}
#[test]
fn unknown_functions_are_ignored_but_nested_calls_are_checked() {
assert!(expression_errors("FOO ( 1, 2, 3 )").is_empty());
assert!(expression_errors("CALCULATE ( SUM ( Sales[Amount] ), Sales[Region] = \"East\" )").is_empty());
assert!(call_errors("FOO ( 1, 2, 3 )").is_empty());
let errors = expression_errors("CALCULATE ( SUM ( 1 ) )");
assert_eq!(errors.len(), 1, "{errors:?}");
assert_eq!(errors[0].function, "SUM");
assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind);
}
#[test]
fn validate_call_reports_arities_and_kinds() {
let errors = call_errors("MAX ( 1, 2, 3 )");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].kind, ValidationErrorKind::Arity);
// `Call` has no own span; the expression validator supplies it.
assert!(errors[0].span.is_empty());
let errors = call_errors("SUM ( 1 )");
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind);
assert!(!errors[0].span.is_empty());
assert!(call_errors("SUM ( Sales[Amount] )").is_empty());
assert!(call_errors("COUNTROWS ( )").is_empty());
}
#[test]
fn validate_expression_reports_every_error_with_a_span() {
let src = "SUM ( 1 ) + AVERAGE ( 2 ) + MAX ( 3 )";
let errors = expression_errors(src);
assert_eq!(errors.len(), 3, "{errors:?}");
for error in &errors {
assert!(!error.span.is_empty(), "{error:?}");
assert!(error.span.end <= src.len(), "{error:?}");
}
let arguments: Vec<&str> = errors.iter().map(|error| &src[error.span.start..error.span.end]).collect();
assert_eq!(arguments, ["1", "2", "3"]);
let src = "MAX ( 1, 2, 3 )";
let errors = expression_errors(src);
assert_eq!(errors.len(), 1);
assert_eq!(errors[0].kind, ValidationErrorKind::Arity);
assert_eq!(&src[errors[0].span.start..errors[0].span.end], src);
let src = "COUNTROWS ( 1 )";
let errors = expression_errors(src);
assert_eq!(errors.len(), 1);
assert_eq!(&src[errors[0].span.start..errors[0].span.end], "1");
}
-318
View File
@@ -1,318 +0,0 @@
//! Model metadata and name-binding tests.
use gridcraft_dax::binder::{BoundExpr, BoundVariable};
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::{Binder, parse_expression};
fn sample_model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
],
rows: vec![],
},
ModelTable { name: "Date".into(), columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }], rows: vec![] },
],
relationships: vec![Relationship {
from_table: "Sales".into(),
from_column: "Region".into(),
to_table: "Date".into(),
to_column: "Date".into(),
bidirectional: false,
inactive: false,
}],
measures: vec![
Measure { name: "Total Sales".into(), formula: "SUM ( Sales[Amount] )".into(), table: Some("Sales".into()), format: None, expr: None },
Measure {
name: "East Sales".into(),
formula: "CALCULATE ( [Total Sales], Sales[Region] = \"East\" )".into(),
table: Some("Sales".into()),
format: None,
expr: None,
},
Measure { name: "Cycle A".into(), formula: "[Cycle B]".into(), table: None, format: None, expr: None },
Measure { name: "Cycle B".into(), formula: "[Cycle A]".into(), table: None, format: None, expr: None },
],
};
model.parse_formulas().expect("model parses");
model
}
fn bind(model: &DataModel, formula: &str) -> BoundExpr {
let expr = parse_expression(formula).expect("formula parses");
Binder::new(model).bind_expression(&expr).expect("formula binds")
}
#[test]
fn binds_qualified_columns_tables_and_measures() {
let model = sample_model();
match bind(&model, "SUM ( Sales[Amount] )") {
BoundExpr::Call { spec, args } => {
assert_eq!(spec.name, "SUM");
match &args[0] {
BoundExpr::Column { table, column } => {
assert_eq!(model.tables[*table].name, "Sales");
assert_eq!(model.tables[*table].columns[*column].name, "Amount");
}
other => panic!("expected column, got {other:?}"),
}
}
other => panic!("expected call, got {other:?}"),
}
assert!(matches!(bind(&model, "Sales"), BoundExpr::Table(0)));
assert!(matches!(bind(&model, "[Total Sales]"), BoundExpr::Measure(0)));
// A measure reference may carry its home table as a qualifier.
assert!(matches!(bind(&model, "Sales[Total Sales]"), BoundExpr::Measure(0)));
assert!(matches!(bind(&model, "[Amount]"), BoundExpr::UnqualifiedColumn { .. }));
}
#[test]
fn reports_unknown_names_and_bad_arities() {
let model = sample_model();
let error = |formula: &str| {
let expr = parse_expression(formula).expect("parses");
Binder::new(&model).bind_expression(&expr).expect_err("should fail")
};
assert!(error("Missing[Amount]").message.contains("unknown table"));
assert!(error("Sales[Missing]").message.contains("unknown column"));
// A measure qualifier has to name the measure's home table.
assert!(error("Date[Total Sales]").message.contains("belongs to table `Sales`"));
assert!(error("SUM ( )").message.contains("expects 1"));
assert!(error("NOPE ( 1 )").message.contains("unknown DAX function"));
}
#[test]
fn binds_var_return_with_sequential_scopes() {
let model = sample_model();
let bound = bind(&model, "VAR x = 1 VAR y = x + 1 RETURN y");
match bound {
BoundExpr::VarReturn { vars, body } => {
assert_eq!(vars.len(), 2);
assert_eq!(vars[0].name, "x");
assert_eq!(vars[1].name, "y");
assert!(matches!(vars[0], BoundVariable { .. }));
assert!(matches!(*body, BoundExpr::Variable { index: 1, .. }));
}
other => panic!("expected VAR block, got {other:?}"),
}
// A variable shadows a table of the same name.
assert!(matches!(
bind(&model, "VAR Sales = 1 RETURN Sales"),
BoundExpr::VarReturn { body, .. } if matches!(*body, BoundExpr::Variable { .. })
));
}
#[test]
fn bracketed_names_bind_measures_before_variables() {
let mut model = DataModel {
tables: vec![ModelTable {
name: "Sales".into(),
columns: vec![ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }],
rows: vec![],
}],
relationships: vec![],
measures: vec![Measure {
name: "Total".into(),
formula: "SUM ( Sales[Amount] )".into(),
table: Some("Sales".into()),
format: None,
expr: None,
}],
};
model.parse_formulas().expect("model parses");
// `[Total]` is a bracketed model reference, so it binds to the measure even though a
// variable of the same name is in scope.
match bind(&model, "VAR Total = 1 RETURN [Total]") {
BoundExpr::VarReturn { vars, body } => {
assert_eq!(vars.len(), 1);
assert_eq!(vars[0].name, "Total");
assert!(matches!(*body, BoundExpr::Measure(0)), "expected measure, got {body:?}");
}
other => panic!("expected VAR block, got {other:?}"),
}
// A bare name still resolves to the variable.
assert!(matches!(
bind(&model, "VAR Total = 1 RETURN Total"),
BoundExpr::VarReturn { body, .. } if matches!(*body, BoundExpr::Variable { index: 0, .. })
));
}
#[test]
fn pathitem_type_names_bind_as_keywords() {
let model = sample_model();
for (formula, function, expected) in
[("PATHITEM ( \"1|2\", 1, TEXT )", "PATHITEM", "TEXT"), ("PATHITEMREVERSE ( \"1|2\", 1, INTEGER )", "PATHITEMREVERSE", "INTEGER")]
{
match bind(&model, formula) {
BoundExpr::Call { spec, args } => {
assert_eq!(spec.name, function);
assert_eq!(args.len(), 3);
assert!(matches!(&args[2], BoundExpr::Keyword(keyword) if keyword == expected), "expected `{expected}` keyword, got {:?}", args[2]);
}
other => panic!("expected call, got {other:?}"),
}
}
}
#[test]
fn measures_and_dependencies_are_bound() {
let model = sample_model();
let binder = Binder::new(&model);
let total = binder.bind_measure("Total Sales").expect("measure binds");
assert!(total.dependencies.is_empty());
let east = binder.bind_measure("East Sales").expect("measure binds");
assert_eq!(east.dependencies, ["Total Sales".to_string()].into_iter().collect());
let graph = binder.dependency_graph().expect_err("cycle is rejected");
assert!(graph.message.contains("circular"));
}
#[test]
fn model_validation_rejects_duplicates_and_missing_relationship_columns() {
let mut model = sample_model();
model.tables.push(ModelTable { name: "sales".into(), columns: vec![], rows: vec![] });
assert!(model.parse_formulas().expect_err("duplicate table").message.contains("duplicate"));
let mut model = sample_model();
model.relationships.push(Relationship {
from_table: "Sales".into(),
from_column: "Missing".into(),
to_table: "Date".into(),
to_column: "Date".into(),
bidirectional: false,
inactive: false,
});
assert!(model.parse_formulas().expect_err("missing column").message.contains("missing column"));
}
#[test]
fn model_json_deserializes_and_parses_measures() {
let json = r#"{
"tables": [{"name":"Sales","columns":[{"name":"Amount","data_type":"Double"}]}],
"relationships": [],
"measures": [{"name":"Total","formula":"SUM(Sales[Amount])","table":"Sales"}]
}"#;
let mut model: DataModel = serde_json::from_str(json).expect("json loads");
model.parse_formulas().expect("model parses");
assert!(model.measures[0].expr.is_some());
}
#[test]
fn documented_keyword_arguments_bind_instead_of_resolving_as_names() {
let model = sample_model();
// CROSSFILTER's direction words are documented enum values, including the two directional
// spellings; none of them may be resolved as a model name.
for direction in ["NONE", "ONE", "ONEWAY", "BOTH", "TWOWAY", "ONEWAY_LEFTFILTERSRIGHT", "ONEWAY_RIGHTFILTERSLEFT"] {
let formula = format!("CROSSFILTER ( Sales[Region], Date[Date], {direction} )");
match bind(&model, &formula) {
BoundExpr::Call { args, .. } => {
assert!(matches!(&args[2], BoundExpr::Keyword(word) if word.eq_ignore_ascii_case(direction)), "{direction}: {:?}", args[2]);
}
other => panic!("expected a call for {direction}, got {other:?}"),
}
}
// RANK/ROWNUMBER's Reset argument takes the same three words at the documented position.
for reset in ["NONE", "LOWESTPARENT", "HIGHESTPARENT"] {
let rank =
format!("RANK ( DENSE, Sales, ORDERBY ( Sales[Amount] ), DEFAULT, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[Amount] ), {reset} )");
assert!(matches!(bind(&model, &rank), BoundExpr::Call { .. }), "RANK should bind {reset}");
let rownumber =
format!("ROWNUMBER ( Sales, ORDERBY ( Sales[Amount] ), DEFAULT, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[Amount] ), {reset} )");
assert!(matches!(bind(&model, &rownumber), BoundExpr::Call { .. }), "ROWNUMBER should bind {reset}");
}
// RANKX's Order argument is `ASC`/`DESC`, not a name.
match bind(&model, "RANKX ( Sales, Sales[Amount], 42, DESC )") {
BoundExpr::Call { args, .. } => assert!(matches!(args[3], BoundExpr::Keyword(ref word) if word == "DESC"), "{:?}", args[3]),
other => panic!("expected a call, got {other:?}"),
}
}
#[test]
fn an_interval_keyword_is_not_shadowed_by_a_variable() {
let model = sample_model();
// A variable in scope must not turn the documented interval argument into a name: `YEAR` here
// is DATEDIFF's interval, and the binder keeps it a keyword.
let bound = bind(&model, "VAR YEAR = 1 RETURN DATEDIFF ( Sales[Amount], Sales[Amount], YEAR )");
let debug = format!("{bound:?}");
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
// A variable still wins where the parameter is documented as text: RANKX's Ties argument.
let bound = bind(&model, "VAR DENSE = 1 RETURN RANKX ( Sales, Sales[Amount], 42, DENSE )");
assert!(format!("{bound:?}").contains("Variable"), "{bound:?}");
}
#[test]
fn documented_order_keywords_bind_at_their_argument_positions() {
let model = sample_model();
// Each documented bare `ASC`/`DESC` slot binds as a keyword instead of failing as an unknown
// name, and an undocumented word there is still a name (and therefore an unknown one).
let calls = [
("RANKX ( Sales, Sales[Amount], 42, DESC )", 3),
("RANK.EQ ( 42, Sales[Amount], DESC )", 2),
("TOPNSKIP ( 10, 20, Sales, Sales[Amount], DESC )", 4),
("CONCATENATEX ( Sales, Sales[Amount], \", \", Sales[Amount], DESC )", 4),
("SAMPLE ( 10, Sales, Sales[Amount], DESC )", 3),
];
for (src, position) in calls {
match bind(&model, src) {
BoundExpr::Call { args, .. } => {
assert!(matches!(&args[position], BoundExpr::Keyword(word) if word == "DESC"), "{src}: {:?}", args[position]);
}
other => panic!("{src}: expected a call, got {other:?}"),
}
}
// Every repeated `(orderBy, Order)` pair binds, not just the first one.
for (src, positions) in [
("SAMPLE ( 10, Sales, Sales[Amount], DESC, Sales[Amount], ASC )", [3usize, 5usize]),
("TOPNSKIP ( 10, 20, Sales, Sales[Amount], DESC, Sales[Amount], ASC )", [4usize, 6usize]),
] {
match bind(&model, src) {
BoundExpr::Call { args, .. } => {
assert!(matches!(&args[positions[0]], BoundExpr::Keyword(word) if word == "DESC"), "{src}: {:?}", args[positions[0]]);
assert!(matches!(&args[positions[1]], BoundExpr::Keyword(word) if word == "ASC"), "{src}: {:?}", args[positions[1]]);
}
other => panic!("{src}: expected a call, got {other:?}"),
}
}
// An unknown word in a keyword slot is still unknown.
let expr = parse_expression("SAMPLE ( 10, Sales, Sales[Amount], SIDEWAYS )").expect("parse");
assert!(Binder::new(&model).bind_expression(&expr).is_err());
}
#[test]
fn concatenate_x_binds_a_bare_order_word_in_every_pair() {
let model = sample_model();
// Every `(orderBy, Order)` pair takes a bare keyword: index 4 and index 6 here.
let bound = bind(&model, "CONCATENATEX ( Sales, Sales[Region], \"|\", Sales[Region], DESC, Sales[Amount], ASC )");
match bound {
BoundExpr::Call { args, .. } => {
assert!(matches!(&args[4], BoundExpr::Keyword(word) if word == "DESC"), "{:?}", args[4]);
assert!(matches!(&args[6], BoundExpr::Keyword(word) if word == "ASC"), "{:?}", args[6]);
}
other => panic!("expected a call, got {other:?}"),
}
// A non-keyword in an order slot is still a name, and there is no such name here.
let expr = parse_expression("CONCATENATEX ( Sales, Sales[Region], \"|\", Sales[Region], SIDEWAYS )").expect("parse");
assert!(Binder::new(&model).bind_expression(&expr).is_err());
}
#[test]
fn a_datatable_type_word_is_never_a_table_name() {
let mut model = sample_model();
// A table called `INTEGER` must not capture DATATABLE's type word.
model.tables.push(gridcraft_dax::model::ModelTable {
name: "INTEGER".into(),
columns: vec![gridcraft_dax::model::ModelColumn { name: "Id".into(), data_type: Some("Int64".into()) }],
rows: Vec::new(),
});
match bind(&model, "DATATABLE ( \"Id\", INTEGER, { { 1 } } )") {
BoundExpr::Call { args, .. } => assert!(matches!(&args[1], BoundExpr::Keyword(word) if word == "INTEGER"), "{:?}", args[1]),
other => panic!("expected a call, got {other:?}"),
}
}
-85
View File
@@ -1,85 +0,0 @@
//! Cross-category invariants for the complete DAX function catalog.
use std::collections::BTreeMap;
use gridcraft_dax::functions::{FunctionCategory, ReturnType, catalog, lookup};
use gridcraft_dax::parse_expression;
use gridcraft_dax::types::{DataType, InferredType, infer_type};
#[test]
fn every_category_has_functions_and_names_are_unique() {
for category in FunctionCategory::ALL {
let count = catalog().iter().filter(|spec| spec.category == category).count();
assert!(count > 0, "{} has no functions", category.name());
}
let mut names = BTreeMap::new();
for spec in catalog() {
if let Some(previous) = names.insert(spec.name, spec.category) {
panic!("{} appears in both {} and {}", spec.name, previous.name(), spec.category.name());
}
}
assert_eq!(names.len(), catalog().len());
}
#[test]
fn records_have_consistent_signatures_and_parseable_examples() {
for spec in catalog() {
assert!(!spec.name.is_empty(), "empty name");
assert!(!spec.description.is_empty(), "{} has no description", spec.name);
assert!(!spec.examples.is_empty(), "{} has no examples", spec.name);
assert!(spec.min_args <= spec.max_args, "{} has min > max", spec.name);
let variadic = spec.overloads.iter().any(|overload| overload.variadic);
if variadic {
assert!(
spec.overloads.iter().any(|overload| overload.matches(spec.min_args)),
"{} has no variadic overload for min arity {}",
spec.name,
spec.min_args
);
assert!(
spec.overloads.iter().any(|overload| overload.matches(spec.max_args)),
"{} has no overload for max arity {}",
spec.name,
spec.max_args
);
} else {
assert_eq!(spec.params.len(), spec.max_args, "{} descriptive params", spec.name);
let required = spec.params.iter().filter(|param| !param.optional).count();
let optional = spec.params.iter().filter(|param| param.optional).count();
assert_eq!(required, spec.min_args, "{} required params", spec.name);
assert_eq!(optional, spec.max_args - spec.min_args, "{} optional params", spec.name);
for arity in spec.min_args..=spec.max_args {
assert!(spec.overload_for(arity).is_some(), "{} has no overload for arity {arity}", spec.name);
}
}
for example in spec.examples {
assert!(parse_expression(example).is_ok(), "{} example does not parse: {example}", spec.name);
}
assert!(lookup(&spec.name.to_ascii_lowercase()).is_some(), "{} lookup", spec.name);
}
}
#[test]
fn catalogued_zero_argument_functions_expose_their_return_type() {
for spec in catalog().iter().filter(|spec| spec.min_args == 0) {
let source = format!("{}()", spec.name);
let expr = parse_expression(&source).unwrap_or_else(|error| panic!("{source}: {error}"));
let expected = match spec.return_type {
ReturnType::Integer => InferredType::Data(DataType::Integer),
ReturnType::Decimal => InferredType::Data(DataType::Decimal),
ReturnType::Numeric => InferredType::Unknown,
ReturnType::Currency => InferredType::Data(DataType::Currency),
ReturnType::Boolean => InferredType::Data(DataType::Boolean),
ReturnType::DateTime => InferredType::Data(DataType::DateTime),
ReturnType::String => InferredType::Data(DataType::String),
ReturnType::Variant => InferredType::Data(DataType::Variant),
ReturnType::Table => InferredType::Table,
ReturnType::Blank => InferredType::Blank,
ReturnType::Any => InferredType::Unknown,
};
assert_eq!(infer_type(&expr), Ok(expected), "{} return type", spec.name);
}
}
-188
View File
@@ -1,188 +0,0 @@
//! Every catalogued DAX function must reach an evaluator path.
//!
//! The catalog is the source of truth for the 484 functions. These tests build a minimal call for
//! each spec — at *every* documented arity, using each overload's parameter kinds — bind it
//! against a small model and evaluate it. A structured "not implemented" error, or a bind
//! failure, fails the test: both mean the function has no evaluator path.
//!
//! `catalog_counts_by_category` guards the documented catalog numbers; `catalog_names_are_unique`
//! guards against a duplicate record hiding a missing function.
use gridcraft_dax::functions::{FunctionCategory, ParamKind, ReturnType, catalog};
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{Binder, Evaluator, parse_expression};
/// Whether this build links every evaluator family.
///
/// The evaluator families ship in separate branches, and the crate documents that a function
/// whose family is not linked reports "not implemented". Only a build that links all of them can
/// assert that *no* catalogued function lacks an evaluator path, so the assertion below is armed
/// again automatically as soon as the last family lands.
fn all_families_linked() -> bool {
gridcraft_dax::eval::linked_families().count() == gridcraft_dax::eval::ALL_FAMILIES.len()
}
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) },
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
],
rows: vec![
vec![Scalar::String("East".into()), Scalar::Decimal(10.0), Scalar::Integer(2), Scalar::Boolean(true), Scalar::DateTime(45292.0)],
vec![Scalar::String("West".into()), Scalar::Decimal(20.0), Scalar::Integer(3), Scalar::Boolean(false), Scalar::DateTime(45293.0)],
vec![Scalar::String("East".into()), Scalar::Decimal(30.0), Scalar::Integer(4), Scalar::Boolean(true), Scalar::DateTime(45294.0)],
],
},
ModelTable {
name: "Products".into(),
columns: vec![
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
ModelColumn { name: "Price".into(), data_type: Some("Double".into()) },
],
rows: vec![vec![Scalar::String("Bike".into()), Scalar::Decimal(100.0)], vec![Scalar::String("Helmet".into()), Scalar::Decimal(25.0)]],
},
],
relationships: Vec::new(),
measures: Vec::new(),
};
model.parse_formulas().expect("model parses");
model
}
/// A syntactically valid argument for a catalog parameter kind.
fn placeholder(kind: ParamKind) -> &'static str {
match kind {
ParamKind::Column => "Sales[Amount]",
ParamKind::Table | ParamKind::Reference => "Sales",
ParamKind::Expression => "Sales[Amount]",
ParamKind::Logical | ParamKind::Boolean => "TRUE",
ParamKind::Text => "\"text\"",
ParamKind::Date => "DATE(2024,1,1)",
ParamKind::Function => "SUM",
ParamKind::Number | ParamKind::Scalar | ParamKind::Any | ParamKind::Variant | ParamKind::Json => "1",
}
}
/// Builds a minimal call with `arity` arguments taken from the matching overload (or the
/// descriptive signature when no overload matches, which the shape test rejects).
fn formula(name: &str, arity: usize) -> String {
let spec = gridcraft_dax::functions::lookup(name).expect("catalogued");
let kinds: Vec<ParamKind> = match spec.overload_for(arity) {
Some(overload) => (0..arity).map(|index| overload.kind_at(index).unwrap_or(ParamKind::Any)).collect(),
None => (0..arity).map(|index| spec.params.get(index).map(|param| param.kind).unwrap_or(ParamKind::Any)).collect(),
};
let args: Vec<&str> = kinds.iter().map(|kind| placeholder(*kind)).collect();
format!("{name}({})", args.join(", "))
}
/// Every arity the catalog documents for a function, including the variadic minimum.
fn documented_arities(name: &str) -> Vec<usize> {
let spec = gridcraft_dax::functions::lookup(name).expect("catalogued");
let mut arities: Vec<usize> = spec.overloads.iter().map(|overload| overload.arity()).collect();
arities.push(spec.min_args);
arities.sort_unstable();
arities.dedup();
arities
}
#[test]
fn every_catalogued_function_has_an_evaluator_path() {
let model = model();
let binder = Binder::new(&model);
let evaluator = Evaluator::new(&model).expect("evaluator");
let mut failures = Vec::new();
let mut checked = 0usize;
for spec in catalog() {
for arity in documented_arities(spec.name) {
checked += 1;
let source = formula(spec.name, arity);
let expr = match parse_expression(&source) {
Ok(expr) => expr,
Err(error) => {
failures.push(format!("{}: parse error in `{source}`: {error}", spec.name));
continue;
}
};
let bound = match binder.bind_expression(&expr) {
Ok(bound) => bound,
Err(error) => {
failures.push(format!("{}: bind error in `{source}`: {error}", spec.name));
continue;
}
};
let result = if spec.return_type == ReturnType::Table {
evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64))
} else {
evaluator.evaluate(&bound)
};
if let Err(error) = result
&& error.message.contains("not implemented")
&& all_families_linked()
{
failures.push(format!("{}: `{source}` -> {error}", spec.name));
}
}
}
assert!(checked >= catalog().len(), "every function is checked at least once");
assert!(failures.is_empty(), "{} calls have no evaluator path:\n{}", failures.len(), failures.join("\n"));
}
#[test]
fn catalog_counts_by_category() {
// Guards the documentation numbers: 484 catalogued, split across the documented families.
assert_eq!(catalog().len(), 484);
for category in FunctionCategory::ALL {
assert!(catalog().iter().any(|spec| spec.category == category), "{} has functions", category.name());
}
// The exact split, so a function moving family (or a silently dropped record) fails here
// instead of hiding behind the total.
let expected: [(FunctionCategory, usize); 15] = [
(FunctionCategory::Aggregation, 22),
(FunctionCategory::DateAndTime, 24),
(FunctionCategory::Filter, 29),
(FunctionCategory::Financial, 51),
(FunctionCategory::Information, 114),
(FunctionCategory::Logical, 13),
(FunctionCategory::MathAndTrig, 49),
(FunctionCategory::Other, 16),
(FunctionCategory::ParentChild, 5),
(FunctionCategory::RelationshipManagement, 4),
(FunctionCategory::Statistical, 43),
(FunctionCategory::TableManipulation, 35),
(FunctionCategory::Text, 23),
(FunctionCategory::TimeIntelligence, 45),
(FunctionCategory::VisualCalculations, 11),
];
let mut failures = Vec::new();
for (category, count) in expected {
let actual = catalog().iter().filter(|spec| spec.category == category).count();
if actual != count {
failures.push(format!("{}: {actual} catalogued, documented {count}", category.name()));
}
}
assert!(failures.is_empty(), "catalog family counts drifted:\n{}", failures.join("\n"));
assert_eq!(expected.iter().map(|(_, count)| count).sum::<usize>(), catalog().len(), "the family counts add up to the catalog");
}
#[test]
fn catalog_names_are_unique() {
let mut names: Vec<String> = catalog().iter().map(|spec| spec.name.to_ascii_uppercase()).collect();
let total = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(total, names.len(), "the catalog has duplicate function names");
for spec in catalog() {
assert!(gridcraft_dax::functions::lookup(spec.name).is_some(), "{} is not reachable through lookup", spec.name);
}
}
-569
View File
@@ -1,569 +0,0 @@
//! Data-type, literal and operator-table tests for `gridcraft-dax`.
use gridcraft_dax::ast::{DateTimeLiteral, Expr, ExprKind, Literal};
use gridcraft_dax::types::{
DataType, InferredType, PseudoType, TypeError, arithmetic_type, binary_type, comparison_coercion, comparison_compatible, comparison_type,
infer_type, literal_type, numeric_matrix_order, unary_type,
};
use gridcraft_dax::{BinaryOp, Span, TokenKind, UnaryOp, parse_expression, print_expression, tokenize};
fn parse(src: &str) -> Expr {
match parse_expression(src) {
Ok(expr) => expr,
Err(error) => panic!("{src:?} did not parse: {error}"),
}
}
fn literal(src: &str) -> Literal {
match parse(src).kind {
ExprKind::Literal(literal) => literal,
other => panic!("{src:?} is not a literal: {other:?}"),
}
}
/// Parses, prints, re-parses and asserts the AST is unchanged. Returns the canonical text.
fn round_trip(src: &str) -> String {
let parsed = parse(src);
let printed = print_expression(&parsed);
let reparsed = parse(&printed);
assert_eq!(parsed, reparsed, "round trip changed the AST for {src:?} via {printed:?}");
printed
}
fn infer(src: &str) -> Result<InferredType, TypeError> {
infer_type(&parse(src))
}
fn data(data_type: DataType) -> InferredType {
InferredType::Data(data_type)
}
fn arithmetic(op: BinaryOp, left: DataType, right: DataType) -> Result<InferredType, TypeError> {
arithmetic_type(op, data(left), data(right))
}
#[test]
fn eight_scalar_types_and_metadata() {
assert_eq!(DataType::ALL.map(DataType::name), ["Binary", "Boolean", "Currency", "DateTime", "Decimal", "Integer", "String", "Variant"]);
for data_type in DataType::ALL {
let metadata = data_type.metadata();
assert_eq!(metadata.name, data_type.name());
assert!(!metadata.representation.is_empty(), "{} representation", data_type.name());
assert!(!metadata.range.is_empty(), "{} range", data_type.name());
assert!(!metadata.precision.is_empty(), "{} precision", data_type.name());
assert!(!metadata.notes.is_empty(), "{} notes", data_type.name());
assert_eq!(data_type.has_literal(), metadata.literal_syntax.is_some());
assert!(!metadata.name.is_empty());
}
assert_eq!(DataType::ALL.map(DataType::has_literal), [false, true, false, true, true, true, true, false], "literal availability per type");
assert!(DataType::Binary.metadata().literal_syntax.is_none());
assert!(DataType::Boolean.metadata().literal_syntax.is_some());
assert!(DataType::Currency.metadata().literal_syntax.is_none());
assert!(DataType::DateTime.metadata().literal_syntax.is_some());
assert!(DataType::Decimal.metadata().literal_syntax.is_some());
assert!(DataType::Integer.metadata().literal_syntax.is_some());
assert!(DataType::String.metadata().literal_syntax.is_some());
assert!(DataType::Variant.metadata().literal_syntax.is_none());
assert!(DataType::Integer.is_numeric());
assert!(DataType::Currency.is_numeric());
assert!(DataType::Decimal.is_numeric());
assert!(!DataType::Boolean.is_numeric());
assert!(!DataType::DateTime.is_numeric());
}
#[test]
fn blank_and_table_are_pseudo_types_distinct_from_the_eight() {
assert_eq!(PseudoType::ALL.map(PseudoType::name), ["BLANK", "Table"]);
assert!(DataType::ALL.iter().all(|data_type| data_type.name() != "BLANK"));
assert!(DataType::ALL.iter().all(|data_type| data_type.name() != "Table"));
let blank = PseudoType::Blank.metadata();
assert_eq!(blank.name, "BLANK");
assert!(blank.literal_syntax.is_none(), "BLANK has no literal");
assert!(blank.notes.contains("BLANK()"), "BLANK is a function: {}", blank.notes);
let table = PseudoType::Table.metadata();
assert_eq!(table.name, "Table");
assert!(table.literal_syntax.is_some(), "table constructors exist");
assert!(!table.representation.is_empty());
assert_eq!(InferredType::from(PseudoType::Blank), InferredType::Blank);
assert_eq!(InferredType::from(PseudoType::Table), InferredType::Table);
assert_eq!(InferredType::Blank.name(), "BLANK");
assert_eq!(InferredType::Table.name(), "Table");
assert_eq!(InferredType::Unknown.name(), "unknown");
}
#[test]
fn literal_classification() {
for (src, data_type) in [
("42", DataType::Integer),
("-42", DataType::Integer),
("3.14", DataType::Decimal),
("1e3", DataType::Decimal),
("dt\"2023-05-19\"", DataType::DateTime),
("\"text\"", DataType::String),
("TRUE", DataType::Boolean),
] {
// `-42` is a unary expression, so inspect its operand before classifying.
let expr = parse(src);
let node = match &expr.kind {
ExprKind::Unary { expr, .. } => expr.as_ref(),
_ => &expr,
};
match &node.kind {
ExprKind::Literal(value) => assert_eq!(literal_type(value), data_type, "{src}"),
other => panic!("{src:?} did not contain a literal: {other:?}"),
}
}
}
#[test]
#[allow(clippy::approx_constant)] // 3.14 is the documented Decimal example, not PI.
fn integer_and_decimal_literals_are_distinct() {
assert_eq!(literal("0"), Literal::Integer(0));
assert_eq!(literal("42"), Literal::Integer(42));
assert_eq!(literal("007"), Literal::Integer(7));
assert_eq!(literal("9223372036854775807"), Literal::Integer(i64::MAX));
for (src, value, canonical) in [
("3.14", 3.14, "3.14"),
("1e3", 1000.0, "1000.0"),
("1E3", 1000.0, "1000.0"),
("1.5E-3", 0.0015, "0.0015"),
(".5", 0.5, "0.5"),
("1.", 1.0, "1.0"),
("1.e3", 1000.0, "1000.0"),
("0.000001", 0.000001, "1e-6"),
] {
assert_eq!(literal(src), Literal::Decimal(value), "{src}");
assert_eq!(round_trip(src), canonical, "{src}");
}
// The sign is always the unary operator, never part of the numeric token.
match parse("-42").kind {
ExprKind::Unary { op: UnaryOp::Neg, expr } => {
assert_eq!(expr.kind, ExprKind::Literal(Literal::Integer(42)));
}
other => panic!("expected unary minus, found {other:?}"),
}
match parse("+42").kind {
ExprKind::Unary { op: UnaryOp::Plus, expr } => {
assert_eq!(expr.kind, ExprKind::Literal(Literal::Integer(42)));
}
other => panic!("expected unary plus, found {other:?}"),
}
}
#[test]
fn numeric_literal_overflow_is_a_structured_error() {
for (src, needle) in [
("9223372036854775808", "integer literal is out of range"),
("99999999999999999999999999999999999999", "integer literal is out of range"),
("1e400", "decimal literal is out of range"),
] {
let error = match parse_expression(src) {
Ok(expr) => panic!("{src:?} unexpectedly parsed as {expr:?}"),
Err(error) => error,
};
assert!(error.message.contains(needle), "{}: {}", src, error.message);
assert_eq!(error.span, Span::new(0, src.len()), "{src}");
assert!(error.to_string().contains(&error.span.start.to_string()));
}
// Limitation: the sign is a unary operator, so the unsigned magnitude of i64::MIN cannot be
// written as an Integer literal. The parser reports the overflow instead of wrapping.
assert!(parse_expression("-9223372036854775808").is_err());
}
#[test]
fn lexer_emits_typed_literal_tokens() {
let tokens = match tokenize("1 2.5 dt\"2023-01-01\" \"x\" TRUE") {
Ok(tokens) => tokens,
Err(error) => panic!("tokenization failed: {error}"),
};
assert_eq!(tokens.first().map(|token| &token.kind), Some(&TokenKind::Integer(1)));
assert_eq!(tokens.get(1).map(|token| &token.kind), Some(&TokenKind::Decimal(2.5)));
assert!(matches!(
tokens.get(2).map(|token| &token.kind),
Some(TokenKind::DateTime(DateTimeLiteral { year: 2023, month: 1, day: 1, has_time: false, .. }))
));
assert_eq!(tokens.get(3).map(|token| &token.kind), Some(&TokenKind::String("x".into())));
assert_eq!(tokens.get(4).map(|token| &token.kind), Some(&TokenKind::Ident("TRUE".into())));
}
#[test]
fn datetime_literal_forms_are_accepted_and_canonicalised() {
for (src, canonical) in [
("dt\"2023-05-19\"", "dt\"2023-05-19\""),
("dt\"2023-05-19T14:30:00\"", "dt\"2023-05-19T14:30:00\""),
("dt\"2023-05-19 14:30:00\"", "dt\"2023-05-19T14:30:00\""),
("dt\"2015-1-9T2:3:0\"", "dt\"2015-01-09T02:03:00\""),
("dt\"2023-5-9\"", "dt\"2023-05-09\""),
("dt\"2024-2-29\"", "dt\"2024-02-29\""),
("DT\"2023-5-19\"", "dt\"2023-05-19\""),
] {
assert_eq!(round_trip(src), canonical, "{src}");
}
match literal("dt\"2015-1-9T2:3:0\"") {
Literal::DateTime(value) => {
assert_eq!(value, DateTimeLiteral { year: 2015, month: 1, day: 9, hour: 2, minute: 3, second: 0, has_time: true })
}
other => panic!("expected a DateTime literal, found {other:?}"),
}
}
#[test]
fn datetime_literal_rejects_invalid_forms() {
for src in [
// Timezone offsets and fractional seconds are not part of the DAX literal forms.
"dt\"2023-05-19T14:30:00Z\"",
"dt\"2023-05-19T14:30:00+02:00\"",
"dt\"2023-05-19T14:30:00.123\"",
// Time-only and incomplete values.
"dt\"14:30:00\"",
"dt\"2023-05-19T14:30\"",
"dt\"2023-05\"",
"dt\"20230519\"",
"dt\"23-05-19\"",
"dt\"2023-05-19T\"",
// Invalid calendar fields.
"dt\"2023-02-29\"",
"dt\"1900-02-29\"",
"dt\"2023-13-01\"",
"dt\"2023-00-01\"",
"dt\"2023-04-31\"",
"dt\"2023-01-00\"",
"dt\"2023-01-32\"",
"dt\"0000-01-01\"",
"dt\"2023-05-19T24:00:00\"",
"dt\"2023-05-19T14:60:00\"",
"dt\"2023-05-19T14:30:60\"",
// Wrong case separator; whitespace between prefix and quote.
"dt\"2023-05-19t14:30:00\"",
"dt \"2023-05-19\"",
] {
assert!(parse_expression(src).is_err(), "expected an error for {src:?}");
}
// `dt` alone is an ordinary identifier, not a literal.
assert!(matches!(parse("dt").kind, ExprKind::Name(_)));
let error = match parse_expression("dt\"2023-02-29\"") {
Ok(expr) => panic!("invalid calendar date parsed as {expr:?}"),
Err(error) => error,
};
assert!(error.message.contains("date/time literal"), "{}", error.message);
assert_eq!(error.span, Span::new(0, "dt\"2023-02-29\"".len()));
}
#[test]
fn literal_printing_round_trips() {
for src in [
"0",
"42",
"3.14",
"1e300",
"1.2345678901234568e18",
"dt\"2023-05-19\"",
"dt\"2023-05-19T14:30:00\"",
"\"a\"\"b\"",
"\"\"",
"TRUE",
"FALSE",
"TRUE()",
"BLANK()",
"1 + 2.5",
"(1 + 2) * 3.0",
"dt\"2023-05-19\" + 1",
] {
let printed = round_trip(src);
if let ExprKind::Literal(Literal::Decimal(value)) = parse(&printed).kind {
assert!(value.is_finite(), "{src} printed a non-finite Decimal");
assert!(printed.contains('.') || printed.contains('e') || printed.contains('E'), "Decimal text must re-lex as a Decimal: {printed}");
}
}
}
#[test]
fn boolean_literals_are_distinct_from_boolean_calls() {
assert_eq!(literal("TRUE"), Literal::Boolean(true));
assert_eq!(literal("FALSE"), Literal::Boolean(false));
for (src, spelling) in [("TRUE()", "TRUE"), ("true()", "true"), ("FALSE()", "FALSE")] {
match parse(src).kind {
ExprKind::Call(call) => {
assert!(call.args.is_empty());
assert_eq!(call.name.text, spelling);
assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}");
}
other => panic!("{src:?} is not a call: {other:?}"),
}
}
// `TRUE(1)` is still a call and is not a literal; the catalog return type is Boolean even
// though arity validation rejects the call.
assert!(matches!(parse("TRUE(1)").kind, ExprKind::Call(_)));
assert_eq!(infer("TRUE(1)"), Ok(data(DataType::Boolean)));
assert_eq!(infer("FALSE(1)"), Ok(data(DataType::Boolean)));
}
#[test]
fn blank_is_a_call_not_a_literal() {
match parse("BLANK()").kind {
ExprKind::Call(call) => {
assert_eq!(call.name.text, "BLANK");
assert!(call.args.is_empty());
}
other => panic!("BLANK() is a call: {other:?}"),
}
assert_eq!(infer("BLANK()"), Ok(InferredType::Blank));
assert!(matches!(parse("BLANK").kind, ExprKind::Name(_)));
assert_eq!(infer("BLANK"), Ok(InferredType::Unknown));
}
#[test]
fn literal_operator_inference() {
for (src, expected) in [
("1 + 2", data(DataType::Integer)),
("1 - 2", data(DataType::Integer)),
("1 * 2", data(DataType::Integer)),
("1 / 2", data(DataType::Decimal)),
("1.0 + 2", data(DataType::Decimal)),
("1 + 2.0", data(DataType::Decimal)),
("2 ^ 3", data(DataType::Decimal)),
("1 & 2", data(DataType::String)),
// Excel: 12&34 is "1234"; the observed result is evaluator output, the type is String.
("12 & 34", data(DataType::String)),
("1 = 2", data(DataType::Boolean)),
// Excel: "Report" = "REPORT" is TRUE (case-insensitive collation is evaluator work).
("\"Report\" = \"REPORT\"", data(DataType::Boolean)),
("1 <> 2", data(DataType::Boolean)),
("1 < 2", data(DataType::Boolean)),
("1 > 2", data(DataType::Boolean)),
("1 <= 2", data(DataType::Boolean)),
("1 >= 2", data(DataType::Boolean)),
("1 == 1", data(DataType::Boolean)),
("TRUE && FALSE", data(DataType::Boolean)),
("TRUE || FALSE", data(DataType::Boolean)),
("NOT TRUE", data(DataType::Boolean)),
("1 IN { 1 }", data(DataType::Boolean)),
("(1, \"a\") IN { (1, \"a\") }", data(DataType::Boolean)),
("TRUE() + 1", data(DataType::Integer)),
("-1", data(DataType::Integer)),
("+1", data(DataType::Integer)),
("-1.5", data(DataType::Decimal)),
("-TRUE()", data(DataType::Integer)),
("dt\"2023-05-19\" + 1", data(DataType::DateTime)),
("1 + dt\"2023-05-19\"", data(DataType::DateTime)),
("dt\"2023-05-19\" - 1", data(DataType::DateTime)),
("dt\"2023-05-19\" - dt\"2023-05-20\"", data(DataType::DateTime)),
("SUM(1, 2)", InferredType::Unknown),
("VALUES(T[Col])", InferredType::Table),
] {
assert_eq!(infer(src), Ok(expected), "{src}");
}
for src in ["[Amount]", "\"22\" + 22", "[Amount] + 1", "[Amount] - 1"] {
assert_eq!(infer(src), Ok(InferredType::Unknown), "{src}");
}
}
#[test]
fn blank_arithmetic_keeps_blank_polymorphic() {
for (src, expected) in [
("BLANK() + 5", data(DataType::Integer)),
("5 + BLANK()", data(DataType::Integer)),
("BLANK() + 2.5", data(DataType::Decimal)),
("BLANK() + TRUE()", data(DataType::Integer)),
("BLANK() + dt\"2023-05-19\"", data(DataType::DateTime)),
("BLANK() + BLANK()", InferredType::Blank),
("BLANK() - BLANK()", InferredType::Blank),
("BLANK() * 5", InferredType::Blank),
("5 * BLANK()", InferredType::Blank),
("BLANK() * BLANK()", InferredType::Blank),
("5 / BLANK()", data(DataType::Decimal)),
("0 / BLANK()", data(DataType::Decimal)),
("BLANK() / 5", InferredType::Blank),
("BLANK() / BLANK()", InferredType::Blank),
("-BLANK()", InferredType::Blank),
] {
assert_eq!(infer(src), Ok(expected), "{src}");
}
assert_eq!(infer("BLANK() + [Amount]"), Ok(InferredType::Unknown));
assert_eq!(infer("BLANK() * [Amount]"), Ok(InferredType::Blank));
}
#[test]
fn incompatible_comparisons_and_coercions() {
for src in ["TRUE() = 1", "1 = TRUE()", "\"1\" = 1", "1 = \"1\"", "\"1\" > 0", "TRUE() == 1", "\"1\" == 1"] {
let error = match infer(src) {
Ok(inferred) => panic!("{src:?} unexpectedly inferred {inferred:?}"),
Err(error) => error,
};
assert!(matches!(error, TypeError::IncompatibleOperands { .. }), "{src}: {error:?}");
assert!(error.to_string().contains("cannot combine"), "{error}");
}
// BLANK is coerced to 0, "" or FALSE for `=`, and comparisons still yield Boolean.
for src in ["BLANK() = 0", "BLANK() <> 0", "BLANK() = \"\"", "BLANK() = FALSE()", "BLANK() = BLANK()"] {
assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}");
}
// `==` is strict and does not coerce BLANK, but the comparison is still well-typed.
for src in ["BLANK() == 0", "BLANK() == \"\"", "0 == BLANK()"] {
assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}");
}
assert_eq!(comparison_coercion(InferredType::Blank, data(DataType::Integer)), Ok(data(DataType::Integer)));
assert_eq!(comparison_coercion(InferredType::Blank, data(DataType::String)), Ok(data(DataType::String)));
assert_eq!(comparison_coercion(data(DataType::Boolean), InferredType::Blank), Ok(data(DataType::Boolean)));
assert_eq!(comparison_coercion(InferredType::Blank, InferredType::Blank), Ok(InferredType::Blank));
assert_eq!(comparison_coercion(data(DataType::Integer), data(DataType::Currency)), Ok(data(DataType::Currency)));
assert_eq!(
comparison_coercion(data(DataType::String), data(DataType::Integer)),
Err(TypeError::IncompatibleTypes { left: data(DataType::String), right: data(DataType::Integer) })
);
assert_eq!(
comparison_coercion(data(DataType::Boolean), data(DataType::Integer)),
Err(TypeError::IncompatibleTypes { left: data(DataType::Boolean), right: data(DataType::Integer) })
);
assert_eq!(
comparison_coercion(InferredType::Table, InferredType::Blank),
Err(TypeError::IncompatibleTypes { left: InferredType::Table, right: InferredType::Blank })
);
assert_eq!(comparison_compatible(BinaryOp::StrictEq, InferredType::Blank, data(DataType::Integer)), Ok(()));
assert_eq!(
comparison_compatible(BinaryOp::Eq, data(DataType::String), data(DataType::Integer)),
Err(TypeError::IncompatibleOperands { op: BinaryOp::Eq, left: data(DataType::String), right: data(DataType::Integer) })
);
assert_eq!(
comparison_compatible(BinaryOp::Eq, InferredType::Table, data(DataType::Integer)),
Err(TypeError::IncompatibleOperands { op: BinaryOp::Eq, left: InferredType::Table, right: data(DataType::Integer) })
);
assert_eq!(comparison_type(BinaryOp::Eq, data(DataType::Integer), data(DataType::Decimal)), Ok(DataType::Boolean));
}
#[test]
fn documented_arithmetic_result_matrices() {
use DataType::{Currency, DateTime, Decimal, Integer};
assert_eq!(numeric_matrix_order(), [Integer, Currency, Decimal, DateTime], "matrix order is Integer, Currency, Real, DateTime");
for (op, left, right, expected) in [
// Addition: DateTime wins; Currency promotes against Integer and Decimal.
(BinaryOp::Add, Integer, Integer, Integer),
(BinaryOp::Add, Integer, Currency, Currency),
(BinaryOp::Add, Currency, Decimal, Decimal),
(BinaryOp::Add, Integer, DateTime, DateTime),
(BinaryOp::Add, DateTime, Integer, DateTime),
(BinaryOp::Add, DateTime, DateTime, DateTime),
// Subtraction: two dates are documented as DateTime.
(BinaryOp::Sub, Integer, Integer, Integer),
(BinaryOp::Sub, Integer, Currency, Currency),
(BinaryOp::Sub, Integer, DateTime, Decimal),
(BinaryOp::Sub, DateTime, Integer, DateTime),
(BinaryOp::Sub, DateTime, DateTime, DateTime),
// Multiplication reproduces the quirky published cells, including INT*DT -> INT.
(BinaryOp::Mul, Integer, Integer, Integer),
(BinaryOp::Mul, Integer, Currency, Currency),
(BinaryOp::Mul, Currency, Currency, Decimal),
(BinaryOp::Mul, Integer, DateTime, Integer),
(BinaryOp::Mul, Currency, DateTime, Currency),
(BinaryOp::Mul, Decimal, DateTime, Decimal),
// Division is Decimal for Integer/Integer and keeps the published Currency cells.
(BinaryOp::Div, Integer, Integer, Decimal),
(BinaryOp::Div, Integer, Currency, Currency),
(BinaryOp::Div, Currency, Currency, Decimal),
(BinaryOp::Div, Currency, Integer, Currency),
(BinaryOp::Div, DateTime, DateTime, Decimal),
(BinaryOp::Div, DateTime, Currency, Decimal),
] {
assert_eq!(arithmetic(op, left, right), Ok(data(expected)), "{op:?} {left:?} {right:?}");
}
// The multiplication table has no DateTime row; DateTime on the left is a type error.
assert!(arithmetic(BinaryOp::Mul, DateTime, Integer).is_err());
assert!(arithmetic(BinaryOp::Mul, DateTime, DateTime).is_err());
}
#[test]
fn documented_comparison_matrix_and_date_comparisons() {
use DataType::{Currency, DateTime, Decimal, Integer};
for (left, right, expected) in [
(Integer, Integer, Integer),
(Integer, Currency, Currency),
(Currency, Currency, Currency),
(Integer, Decimal, Decimal),
(Integer, DateTime, Decimal),
(Currency, DateTime, Decimal),
(DateTime, DateTime, DateTime),
] {
assert_eq!(comparison_coercion(data(left), data(right)), Ok(data(expected)), "{left:?} vs {right:?}");
}
for op in [BinaryOp::Eq, BinaryOp::Ne, BinaryOp::Lt, BinaryOp::Gt, BinaryOp::Le, BinaryOp::Ge, BinaryOp::StrictEq] {
assert_eq!(comparison_type(op, data(DateTime), data(DateTime)), Ok(DataType::Boolean), "date vs date with {op:?}");
assert_eq!(comparison_type(op, data(DateTime), data(Integer)), Ok(DataType::Boolean), "date vs number with {op:?}");
}
assert_eq!(infer("dt\"2023-05-19\" = dt\"2023-05-20\""), Ok(data(DataType::Boolean)));
assert_eq!(infer("dt\"2023-05-19\" < 1"), Ok(data(DataType::Boolean)));
}
#[test]
fn variant_and_binary_have_no_literals_or_operators() {
assert!(DataType::Variant.metadata().literal_syntax.is_none());
assert!(DataType::Binary.metadata().literal_syntax.is_none());
assert!(matches!(parse("VARIANT").kind, ExprKind::Name(_)));
// Container children still participate in inference.
assert!(infer("{ 1 + { 2 } }").is_err());
assert!(infer("(1 + { 2 })").is_err());
assert!(infer("SUM(1 + { 2 })").is_err());
assert!(infer("VAR x = 1 + { 2 } RETURN 1").is_err());
// Catalogued functions expose their documented return type; unknown names stay unknown.
assert_eq!(infer("SUM(Sales[Amount])"), Ok(InferredType::Unknown));
assert_eq!(infer("NOT_A_DAX_FUNCTION(1)"), Ok(InferredType::Unknown));
assert!(matches!(parse("BINARY").kind, ExprKind::Name(_)));
assert_eq!(infer("VARIANT"), Ok(InferredType::Unknown));
assert_eq!(infer("BINARY"), Ok(InferredType::Unknown));
}
#[test]
fn unary_and_binary_type_helpers_reject_non_scalars() {
assert_eq!(unary_type(UnaryOp::Neg, data(DataType::Decimal)), Ok(data(DataType::Decimal)));
assert_eq!(unary_type(UnaryOp::Neg, data(DataType::DateTime)), Ok(data(DataType::DateTime)));
assert_eq!(unary_type(UnaryOp::Plus, data(DataType::Currency)), Ok(data(DataType::Currency)));
assert!(unary_type(UnaryOp::Neg, InferredType::Table).is_err());
assert!(unary_type(UnaryOp::Neg, data(DataType::Binary)).is_err());
assert_eq!(
unary_type(UnaryOp::Not, InferredType::Table),
Err(TypeError::IncompatibleUnaryOperand { op: UnaryOp::Not, operand: InferredType::Table })
);
assert_eq!(binary_type(BinaryOp::Concat, data(DataType::Integer), data(DataType::Boolean)), Ok(data(DataType::String)));
assert_eq!(binary_type(BinaryOp::And, InferredType::Blank, data(DataType::Boolean)), Ok(data(DataType::Boolean)));
assert!(binary_type(BinaryOp::Concat, InferredType::Table, data(DataType::Integer)).is_err());
assert!(binary_type(BinaryOp::In, data(DataType::Integer), data(DataType::Integer)).is_err());
assert_eq!(binary_type(BinaryOp::In, data(DataType::Integer), InferredType::Table), Ok(data(DataType::Boolean)));
assert_eq!(binary_type(BinaryOp::Eq, data(DataType::Boolean), data(DataType::Boolean)), Ok(data(DataType::Boolean)));
}
#[test]
fn table_calls_are_unknown_in_scalar_operand_positions() {
// A table-valued call may resolve to one row/column at evaluation time, so scalar operators
// accept it as unknown rather than rejecting a valid formula.
for src in ["LASTDATE('Date'[Date]) - 1", "FIRSTDATE('Date'[Order Date]) < TODAY()", "-VALUES(Sales[Amount])"] {
assert!(infer(src).is_ok(), "{src} should infer: {:?}", infer(src));
}
assert_eq!(infer("LASTDATE('Date'[Date]) - 1"), Ok(InferredType::Unknown));
// `IN` keeps its operands typed: the left must not be a table.
let error = infer("VALUES(Sales[Amount]) IN { 1 }").expect_err("a table on the left of IN");
assert!(matches!(error, TypeError::IncompatibleOperands { .. }), "{error:?}");
}
-124
View File
@@ -1,124 +0,0 @@
//! Evaluator tests for `AVERAGEA`, `MAXA`, `MINA` and `DISTINCTCOUNTNOBLANK`.
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{Binder, Evaluator, parse_expression};
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) },
ModelColumn { name: "Note".into(), data_type: Some("String".into()) },
ModelColumn { name: "Empty".into(), data_type: Some("String".into()) },
],
rows: vec![
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::Boolean(true), Scalar::String("5".into()), Scalar::Blank],
vec![Scalar::String("West".into()), Scalar::Integer(20), Scalar::Boolean(false), Scalar::String(String::new()), Scalar::Blank],
vec![Scalar::String("East".into()), Scalar::Blank, Scalar::Boolean(true), Scalar::String("abc".into()), Scalar::Blank],
vec![Scalar::Blank, Scalar::Integer(40), Scalar::Boolean(false), Scalar::String("7".into()), Scalar::Blank],
],
}],
relationships: Vec::new(),
measures: Vec::new(),
};
model.parse_formulas().expect("model parses");
model
}
fn eval(src: &str) -> Result<Scalar, String> {
let model = model();
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
let expr = parse_expression(src).map_err(|error| error.to_string())?;
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate(&bound).map_err(|error| error.to_string())
}
fn value(src: &str) -> Scalar {
match eval(src) {
Ok(value) => value,
Err(error) => panic!("{src} failed: {error}"),
}
}
#[test]
fn averagea_counts_text_booleans_and_blanks() {
// Every row counts, a BLANK cell as 0: 10 + 20 + 0 + 40 over four rows. This is the
// documented DAX example (1, 20, "n/a", BLANK and TRUE average 22/5).
assert_eq!(value("AVERAGEA(Sales[Amount])"), Scalar::Decimal(17.5));
// TRUE = 1, FALSE = 0: (1 + 0 + 1 + 0) / 4.
assert_eq!(value("AVERAGEA(Sales[Flag])"), Scalar::Decimal(0.5));
// Any text counts as 0, numeric or not: "5", "", "abc" and "7" all contribute 0.
assert_eq!(value("AVERAGEA(Sales[Note])"), Scalar::Decimal(0.0));
// A column with rows but only BLANK cells averages 0, not BLANK.
assert_eq!(value("AVERAGEA(Sales[Empty])"), Scalar::Decimal(0.0));
}
#[test]
fn averagea_respects_the_filter_context_and_is_blank_for_no_rows() {
// East rows are 10 and BLANK: the BLANK row stays in the denominator.
assert_eq!(value("CALCULATE(AVERAGEA(Sales[Amount]), Sales[Region] = \"East\")"), Scalar::Decimal(5.0));
assert_eq!(value("CALCULATE(AVERAGEA(Sales[Amount]), Sales[Region] = \"Nowhere\")"), Scalar::Blank);
}
#[test]
fn maxa_and_mina_count_logical_values() {
assert_eq!(value("MINA(Sales[Flag])"), Scalar::Decimal(0.0));
assert_eq!(value("MAXA(Sales[Flag])"), Scalar::Decimal(1.0));
// Text is not rankable, so every text value coerces to 0 before the comparison.
assert_eq!(value("MINA(Sales[Note])"), Scalar::Decimal(0.0));
assert_eq!(value("MAXA(Sales[Note])"), Scalar::Decimal(0.0));
assert_eq!(value("MAXA(Sales[Amount])"), Scalar::Decimal(40.0));
assert_eq!(value("MINA(Sales[Amount])"), Scalar::Decimal(10.0));
}
#[test]
fn maxa_and_mina_follow_the_filter_context() {
assert_eq!(value("CALCULATE(MAXA(Sales[Amount]), Sales[Region] = \"East\")"), Scalar::Decimal(10.0));
assert_eq!(value("CALCULATE(MINA(Sales[Amount]), Sales[Region] = \"West\")"), Scalar::Decimal(20.0));
assert_eq!(value("CALCULATE(MAXA(Sales[Flag]), Sales[Region] = \"West\")"), Scalar::Decimal(0.0));
assert_eq!(value("CALCULATE(MAXA(Sales[Amount]), Sales[Region] = \"Nowhere\")"), Scalar::Blank);
}
#[test]
fn distinctcountnoblank_excludes_blank() {
// East, West and one BLANK row -> two distinct non-blank values.
assert_eq!(value("DISTINCTCOUNTNOBLANK(Sales[Region])"), Scalar::Integer(2));
// The plain DISTINCTCOUNT counts BLANK as a value.
assert_eq!(value("DISTINCTCOUNT(Sales[Region])"), Scalar::Integer(3));
assert_eq!(value("DISTINCTCOUNTNOBLANK(Sales[Amount])"), Scalar::Integer(3));
assert_eq!(value("DISTINCTCOUNTNOBLANK(Sales[Empty])"), Scalar::Integer(0));
}
#[test]
fn distinctcountnoblank_respects_the_filter_context() {
// Both East rows carry the same region, so the flag filter leaves one distinct value.
assert_eq!(value("CALCULATE(DISTINCTCOUNTNOBLANK(Sales[Region]), Sales[Flag] = TRUE)"), Scalar::Integer(1));
assert_eq!(value("CALCULATE(DISTINCTCOUNTNOBLANK(Sales[Region]), Sales[Region] = \"Nowhere\")"), Scalar::Integer(0));
}
#[test]
fn the_a_variants_still_require_a_column() {
assert!(eval("AVERAGEA(1)").is_err());
assert!(eval("MAXA(\"text\")").is_err());
assert!(eval("DISTINCTCOUNTNOBLANK()").is_err());
}
#[test]
fn max_and_min_with_two_scalars_return_the_larger_or_smaller_value() {
// The catalog's two-scalar overload, `MAX ( 10000, [Sales Amount] )`.
assert_eq!(value("MAX(3, 5)"), Scalar::Integer(5));
assert_eq!(value("MIN(3, 5)"), Scalar::Integer(3));
assert_eq!(value("MAX(10000, SUM(Sales[Amount]))"), Scalar::Integer(10000));
assert_eq!(value("MIN(1, SUM(Sales[Amount]))"), Scalar::Integer(1));
// Text compares case-insensitively, like every DAX comparison.
assert_eq!(value("MAX(\"a\", \"B\")"), Scalar::String("B".into()));
assert_eq!(value("MIN(\"a\", \"B\")"), Scalar::String("a".into()));
// One argument still aggregates the column, not the first cell. The winner keeps its own
// Scalar type, so an integer column answers an Integer (`aggregate_values` in the core).
assert_eq!(value("MAX(Sales[Amount])"), Scalar::Integer(40));
assert_eq!(value("MIN(Sales[Amount])"), Scalar::Integer(10));
}
-348
View File
@@ -1,348 +0,0 @@
//! Dispatch audit: every catalogued function, at every documented arity, must reach a real
//! evaluator path — never the `not implemented` fallback and never an "unknown function" error.
//!
//! Three tests:
//!
//! 1. [`catalog_shape_is_consistent`] — the catalog itself is coherent: 484 unique names, every
//! documented family populated, overload arities inside `min_args..=max_args`, sugar links
//! resolving.
//! 2. [`no_catalogued_function_reaches_a_stub`] — for every overload arity, the call parses,
//! binds and evaluates, and the outcome is never the generic "not implemented" fallback.
//! 3. [`context_functions_fail_with_a_context_error`] — the functions that legitimately need a
//! visual, calculation-item, row or window context reject a bare model evaluation with a
//! documented context error, never a stub and never a silently wrong value.
//!
//! `INFO.*` metadata functions are not in that list: they evaluate against the model catalogue
//! itself (returning row counts), so the dispatch audit covers them like any other function.
use gridcraft_dax::functions::{FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog};
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{Binder, Evaluator, parse_expression};
/// Whether this build links every evaluator family.
///
/// The evaluator families ship in separate branches, and the crate documents that a function
/// whose family is not linked reports "not implemented". The "no stub" assertions therefore only
/// apply to a build that links all of them; they arm themselves again as soon as the last family
/// lands, so the audit keeps its full strength on the assembled crate.
fn all_families_linked() -> bool {
gridcraft_dax::eval::linked_families().count() == gridcraft_dax::eval::ALL_FAMILIES.len()
}
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) },
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
],
rows: vec![
vec![Scalar::String("East".into()), Scalar::Decimal(10.0), Scalar::Integer(2), Scalar::Boolean(true), Scalar::DateTime(45292.0)],
vec![Scalar::String("West".into()), Scalar::Decimal(20.0), Scalar::Integer(3), Scalar::Boolean(false), Scalar::DateTime(45293.0)],
vec![Scalar::String("East".into()), Scalar::Decimal(30.0), Scalar::Integer(4), Scalar::Boolean(true), Scalar::DateTime(45294.0)],
],
},
ModelTable {
name: "Products".into(),
columns: vec![
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
ModelColumn { name: "Price".into(), data_type: Some("Double".into()) },
],
rows: vec![vec![Scalar::String("Bike".into()), Scalar::Decimal(100.0)], vec![Scalar::String("Helmet".into()), Scalar::Decimal(25.0)]],
},
ModelTable {
name: "Date".into(),
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
rows: vec![vec![Scalar::DateTime(45292.0)], vec![Scalar::DateTime(45293.0)], vec![Scalar::DateTime(45294.0)]],
},
],
relationships: vec![Relationship {
from_table: "Sales".into(),
from_column: "Date".into(),
to_table: "Date".into(),
to_column: "Date".into(),
bidirectional: false,
inactive: false,
}],
measures: Vec::new(),
};
model.parse_formulas().expect("model parses");
model
}
/// A syntactically valid argument for a catalog parameter kind.
fn placeholder(kind: ParamKind) -> &'static str {
match kind {
ParamKind::Column => "Sales[Amount]",
ParamKind::Table | ParamKind::Reference => "Sales",
ParamKind::Expression => "Sales[Amount]",
ParamKind::Logical | ParamKind::Boolean => "TRUE",
ParamKind::Text => "\"text\"",
ParamKind::Date => "DATE(2024,1,1)",
ParamKind::Function => "SUM",
ParamKind::Number | ParamKind::Scalar | ParamKind::Any | ParamKind::Variant | ParamKind::Json => "1",
}
}
/// Builds the call for one arity using that overload's parameter kinds.
fn formula(spec: &FunctionSpec, arity: usize) -> String {
let kinds: Vec<ParamKind> = match spec.overload_for(arity) {
Some(overload) => (0..arity).map(|index| overload.kind_at(index).unwrap_or(ParamKind::Any)).collect(),
None => (0..arity).map(|index| spec.params.get(index).map(|param| param.kind).unwrap_or(ParamKind::Any)).collect(),
};
let args: Vec<&str> = kinds.iter().map(|kind| placeholder(*kind)).collect();
format!("{}({})", spec.name, args.join(", "))
}
/// The exact text the evaluator uses when a function has no implementation. Two sites produce it
/// (`eval.rs` fallback and the time-intelligence range dispatcher), so matching it catches both.
const STUB_MARKER: &str = "is not implemented by this evaluator";
fn is_stub(message: &str) -> bool {
let lower = message.to_ascii_lowercase();
lower.contains(STUB_MARKER) || lower.contains("unknown function") || lower.contains("is not a function")
}
/// Functions that legitimately cannot be evaluated against a bare model: they need a visual, a
/// calculation item, a window/row context or a CALCULATE modifier. Each entry is the *substring the
/// evaluator's context error must contain*.
fn documented_context_requirements() -> Vec<(&'static str, &'static str)> {
let mut list = vec![
("ISSUBTOTAL", "SUMMARIZE row context"),
("CURRENTGROUP", "GROUPBY"),
("ROLLUP", "SUMMARIZE group-by"),
("ROLLUPGROUP", "ROLLUP"),
("ROLLUPADDISSUBTOTAL", "SUMMARIZECOLUMNS"),
("ROLLUPISSUBTOTAL", "ADDMISSINGITEMS"),
("SELECTEDMEASURE", "calculation item"),
("SELECTEDMEASUREFORMATSTRING", "calculation item"),
("SELECTEDMEASURENAME", "calculation item"),
("EARLIER", "outer row context"),
("EARLIEST", "outer row context"),
("RANK", "needs a relation"),
("ROWNUMBER", "needs a relation"),
("OFFSET", "window function"),
("WINDOW", "window function"),
("ORDERBY", "window function"),
("PARTITIONBY", "window function"),
("MATCHBY", "window function"),
("RELATED", "row context"),
("RELATEDTABLE", "row context"),
("CROSSFILTER", "CALCULATE"),
("USERELATIONSHIP", "CALCULATE"),
];
// Visual calculations need a visual frame; they are the whole `VisualCalculations` family.
for spec in catalog() {
if spec.category == FunctionCategory::VisualCalculations && !list.iter().any(|(name, _)| *name == spec.name) {
list.push((spec.name, "visual"));
}
}
list
}
#[test]
fn catalog_shape_is_consistent() {
let specs = catalog();
assert_eq!(specs.len(), 484, "catalogued function count");
let mut seen: Vec<&str> = specs.iter().map(|spec| spec.name).collect();
seen.sort_unstable();
let before = seen.len();
seen.dedup();
assert_eq!(before, seen.len(), "catalog has duplicate names");
for spec in specs {
assert!(spec.min_args <= spec.max_args, "{}: min_args > max_args", spec.name);
assert!(!spec.overloads.is_empty(), "{}: no overloads", spec.name);
assert!(!spec.description.is_empty(), "{}: empty description", spec.name);
for overload in spec.overloads {
assert!(
overload.arity() >= spec.min_args && overload.arity() <= spec.max_args,
"{}: overload arity {} outside {}..={}",
spec.name,
overload.arity(),
spec.min_args,
spec.max_args
);
}
if let Some(target) = spec.sugar_of {
assert!(specs.iter().any(|other| other.name.eq_ignore_ascii_case(target)), "{}: sugar target `{target}` is not catalogued", spec.name);
}
}
let mut counts: Vec<(FunctionCategory, usize)> = FunctionCategory::ALL.iter().map(|category| (*category, 0)).collect();
for spec in specs {
if let Some(entry) = counts.iter_mut().find(|(category, _)| *category == spec.category) {
entry.1 += 1;
}
}
let summary: Vec<String> = counts.iter().map(|(category, count)| format!("{}={count}", category.name())).collect();
println!("catalog: {} functions [{}]", specs.len(), summary.join(", "));
for (category, count) in counts {
assert!(count > 0, "{} has no functions", category.name());
}
}
#[test]
fn no_catalogued_function_reaches_a_stub() {
let model = model();
let binder = Binder::new(&model);
let evaluator = Evaluator::new(&model).expect("evaluator");
let mut checked = 0usize;
let mut valued = 0usize;
let mut blank = 0usize;
let mut rejected = 0usize;
let mut stubs = Vec::new();
let mut bind_failures = Vec::new();
let mut functions_with_a_value = 0usize;
let mut without_value = Vec::new();
for spec in catalog() {
let mut arities: Vec<usize> = spec.overloads.iter().map(|overload| overload.arity()).collect();
arities.push(spec.min_args);
arities.sort_unstable();
arities.dedup();
let mut any_value = false;
let mut first_error = String::new();
for arity in arities {
checked += 1;
let source = formula(spec, arity);
let expr = match parse_expression(&source) {
Ok(expr) => expr,
Err(error) => {
bind_failures.push(format!("{}: parse error in `{source}`: {error}", spec.name));
continue;
}
};
let bound = match binder.bind_expression(&expr) {
Ok(bound) => bound,
Err(error) => {
bind_failures.push(format!("{}: bind error in `{source}`: {error}", spec.name));
continue;
}
};
let result = if spec.return_type == ReturnType::Table {
evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64))
} else {
evaluator.evaluate(&bound)
};
match result {
Ok(Scalar::Blank) => {
blank += 1;
any_value = true;
}
Ok(_) => {
valued += 1;
any_value = true;
}
Err(error) => {
if first_error.is_empty() {
first_error = error.message.clone();
}
if is_stub(&error.message) && all_families_linked() {
stubs.push(format!("{}: `{source}` -> {}", spec.name, error.message));
} else {
rejected += 1;
}
}
}
}
if any_value {
functions_with_a_value += 1;
} else {
without_value.push(format!("{}: {first_error}", spec.name));
}
}
println!(
"dispatch audit: {checked} calls over {} functions — {valued} values, {blank} blanks, {rejected} argument/context rejections, {} stubs",
catalog().len(),
stubs.len()
);
println!("functions that produced at least one value: {functions_with_a_value}");
for line in &without_value {
println!("NO VALUE {line}");
}
assert!(bind_failures.is_empty(), "{} calls do not parse/bind:\n{}", bind_failures.len(), bind_failures.join("\n"));
assert!(stubs.is_empty(), "{} calls reach no evaluator path:\n{}", stubs.len(), stubs.join("\n"));
// Mass-regression guard: with deliberately generic placeholder arguments a majority of
// functions still return a value (the rest reject the argument shape), so a collapse in this
// number means dispatch broke, not that the placeholders changed. A partial build is exempt:
// the families it does not link answer with the documented fallback.
if all_families_linked() {
assert!(
functions_with_a_value * 100 >= catalog().len() * 70,
"only {functions_with_a_value} of {} functions produced a value; dispatch may have regressed",
catalog().len()
);
}
}
#[test]
fn context_functions_fail_with_a_context_error() {
// The list below mixes core functions (`RELATED`, `CROSSFILTER`, `USERELATIONSHIP`) with
// functions owned by evaluator families that ship in other branches, and an unlinked family
// rejects the column argument before it can report its documented context error. The audit
// therefore runs on a build that links every family and re-arms itself as soon as the last
// one lands.
if !all_families_linked() {
return;
}
let model = model();
let binder = Binder::new(&model);
let evaluator = Evaluator::new(&model).expect("evaluator");
let mut problems = Vec::new();
for (name, marker) in documented_context_requirements() {
let spec = catalog().iter().find(|spec| spec.name.eq_ignore_ascii_case(name));
let Some(spec) = spec else {
problems.push(format!("{name}: documented as context-dependent but not catalogued"));
continue;
};
let source = formula(spec, spec.min_args);
let expr = match parse_expression(&source) {
Ok(expr) => expr,
Err(error) => {
problems.push(format!("{name}: parse error in `{source}`: {error}"));
continue;
}
};
let bound = match binder.bind_expression(&expr) {
Ok(bound) => bound,
Err(error) => {
problems.push(format!("{name}: bind error in `{source}`: {error}"));
continue;
}
};
let result = if spec.return_type == ReturnType::Table {
evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64))
} else {
evaluator.evaluate(&bound)
};
match result {
Ok(value) => {
// A value is acceptable only when it is BLANK: the function had nothing to work
// with, which is a documented empty result, not a wrong answer.
if !value.is_blank() {
problems.push(format!("{name}: `{source}` returned {value:?} without a context"));
}
}
Err(error) => {
if is_stub(&error.message) {
problems.push(format!("{name}: `{source}` -> stub: {}", error.message));
} else if !error.message.to_ascii_lowercase().contains(&marker.to_ascii_lowercase()) {
problems.push(format!("{name}: `{source}` -> undocumented error `{}` (expected `{marker}`)", error.message));
}
}
}
}
assert!(problems.is_empty(), "{} context functions do not report a documented context error:\n{}", problems.len(), problems.join("\n"));
}
-202
View File
@@ -1,202 +0,0 @@
//! Semantic audit regressions.
//!
//! Each test pins a documented DAX result that the evaluator used to get wrong. The expected
//! values come from the function contracts in `crates/dax/src/functions/` and from Microsoft's
//! DAX reference; the regression names say which rule is being held.
//!
//! Covered: BLANK's empty-string comparison, `CALCULATE` filters written with `IN` and its
//! removal modifiers, `IF`'s Boolean condition, and the BLANK/Boolean/error propagation rules the
//! audit depends on. The per-function cases (`TRIM`, `MOD`, `ROUNDUP`/`ROUNDDOWN`, `DATEDIFF`,
//! `TIME`, `WEEKDAY`) live with the evaluator families that implement them, under
//! `tests/eval_*.rs`.
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{Binder, Evaluator, parse_expression};
fn model() -> DataModel {
let mut model = DataModel { tables: Vec::new(), relationships: Vec::new(), measures: Vec::new() };
model.parse_formulas().expect("model parses");
model
}
/// One table with a text column and a numeric column, enough for CALCULATE filter tests.
fn sales_model() -> DataModel {
let mut model = DataModel {
tables: vec![ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
],
rows: vec![
vec![Scalar::String("East".into()), Scalar::Decimal(10.0)],
vec![Scalar::String("West".into()), Scalar::Decimal(20.0)],
vec![Scalar::String("East".into()), Scalar::Decimal(30.0)],
vec![Scalar::String("North".into()), Scalar::Decimal(40.0)],
vec![Scalar::String("South".into()), Scalar::Decimal(50.0)],
],
}],
relationships: Vec::new(),
measures: Vec::new(),
};
model.parse_formulas().expect("model parses");
model
}
fn eval_in_sales(source: &str) -> Scalar {
let model = sales_model();
let evaluator = Evaluator::new(&model).expect("evaluator");
let expr = parse_expression(source).expect("parse");
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
evaluator.evaluate(&bound).expect("evaluate")
}
fn eval(source: &str) -> Scalar {
let model = model();
let evaluator = Evaluator::new(&model).expect("evaluator");
let expr = parse_expression(source).expect("parse");
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
evaluator.evaluate(&bound).expect("evaluate")
}
fn error(source: &str) -> String {
let model = model();
let evaluator = Evaluator::new(&model).expect("evaluator");
let expr = parse_expression(source).expect("parse");
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
evaluator.evaluate(&bound).expect_err("evaluate must fail").message
}
fn number(source: &str) -> f64 {
eval(source).to_number().unwrap_or_else(|| panic!("{source} is not numeric: {:?}", eval(source)))
}
#[test]
fn blank_boolean_and_error_propagation() {
// BLANK coerces to 0 in arithmetic and comparisons, but multiplying by BLANK stays BLANK.
assert_eq!(number("BLANK() + 1"), 1.0);
assert_eq!(eval("BLANK() * 5"), Scalar::Blank);
assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true));
assert_eq!(eval("BLANK() == 0"), Scalar::Boolean(false));
assert_eq!(eval("BLANK() & \"x\""), Scalar::String("x".into()));
assert_eq!(eval("ISBLANK(BLANK())"), Scalar::Boolean(true));
// Booleans are 1/0 in arithmetic.
assert_eq!(number("TRUE() + 1"), 2.0);
// The model engine divides by zero without an error: BLANK for 0/0 and the numerator's sign
// of infinity otherwise (Excel's worksheet gives #DIV/0!, DAX does not).
assert_eq!(eval("ISERROR(1/0)"), Scalar::Boolean(false));
assert_eq!(eval("5 / 0"), Scalar::Decimal(f64::INFINITY));
assert_eq!(eval("-5 / 0"), Scalar::Decimal(f64::NEG_INFINITY));
assert_eq!(eval("0 / 0"), Scalar::Blank);
assert_eq!(eval("BLANK() / BLANK()"), Scalar::Blank);
assert_eq!(eval("5 / BLANK()"), Scalar::Decimal(f64::INFINITY));
assert_eq!(eval("BLANK() + BLANK()"), Scalar::Blank);
assert_eq!(eval("BLANK() - BLANK()"), Scalar::Blank);
// Errors still stay errors unless a handler catches them.
assert_eq!(eval("ISERROR(1)"), Scalar::Boolean(false));
assert!(error("ERROR(\"boom\")").contains("boom"));
assert_eq!(number("IFERROR(1/0, 42)"), f64::INFINITY);
assert_eq!(eval("IFERROR(ERROR(\"boom\"), 42)"), Scalar::Integer(42));
assert_eq!(eval("DIVIDE(1, 0)"), Scalar::Blank);
assert_eq!(eval("DIVIDE(1, 0, 99)"), Scalar::Integer(99));
assert_eq!(number("DIVIDE(1, 2)"), 0.5);
}
#[test]
fn blank_compares_as_empty_text_and_as_zero() {
// Excel's DAX: BLANK converts to an empty string against text and to 0 against a number.
// `BLANK () = ""` is TRUE in Excel (observed through the Power Pivot model connection).
assert_eq!(eval("BLANK() = \"\""), Scalar::Boolean(true));
assert_eq!(eval("\"\" = BLANK()"), Scalar::Boolean(true));
assert_eq!(eval("BLANK() <> \"\""), Scalar::Boolean(false));
assert_eq!(eval("BLANK() = \"x\""), Scalar::Boolean(false));
assert_eq!(eval("\"x\" = BLANK()"), Scalar::Boolean(false));
assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true));
assert_eq!(eval("BLANK() = BLANK()"), Scalar::Boolean(true));
// BLANK converts to FALSE against a logical value, so the comparison is TRUE. This case was
// not covered by the Excel sample (BLANK has no worksheet equivalent); it follows the same
// convert-to-the-other-operand rule as the two above.
assert_eq!(eval("BLANK() = FALSE()"), Scalar::Boolean(true));
}
#[test]
fn calculate_filter_accepts_an_in_list() {
// East (10 + 30) plus West (20).
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "East", "West" })"#), Scalar::Decimal(60.0));
// A list of one.
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "North" })"#), Scalar::Decimal(40.0));
// Duplicates in the list do not double-count rows.
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "East", "East", "East" })"#), Scalar::Decimal(40.0));
// A value that is not in the column filters everything out.
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "Nowhere" })"#), Scalar::Blank);
// IN over a single-column table expression.
assert_eq!(
eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN FILTER(VALUES(Sales[Region]), Sales[Region] <> "East"))"#),
Scalar::Decimal(110.0)
);
// The filter form follows DAX equality too: the Decimal column matches an Integer literal.
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Amount] IN { 10 })"#), Scalar::Decimal(10.0));
// The scalar IN operator keeps working.
assert_eq!(eval("1 IN { 1, 2 }"), Scalar::Boolean(true));
assert_eq!(eval("3 IN { 1, 2 }"), Scalar::Boolean(false));
}
#[test]
fn if_requires_a_boolean_condition() {
// Excel rejects a condition it cannot read as logical; it does not take the false branch.
assert!(error(r#"IF("x", 1, 2)"#).contains("IF argument 1 must be Boolean"));
assert!(error(r#"IF("x", 1, 2)"#).contains("String"));
// The documented conditions still work: TRUE, FALSE and BLANK (which converts to FALSE).
assert_eq!(eval("IF(TRUE(), 1, 2)"), Scalar::Integer(1));
assert_eq!(eval("IF(FALSE(), 1, 2)"), Scalar::Integer(2));
assert_eq!(eval("IF(BLANK(), 1, 2)"), Scalar::Integer(2));
assert_eq!(eval("IF(1 > 0, 1, 2)"), Scalar::Integer(1));
}
#[test]
fn strict_equality_compares_values_and_keeps_blank_strict() {
// `==` is strict only about BLANK; every other pair follows DAX comparison, so a number
// compares by value and text ignores case.
assert_eq!(eval("2 == 2.0"), Scalar::Boolean(true));
assert_eq!(eval("1 == 2"), Scalar::Boolean(false));
assert_eq!(eval("\"a\" == \"A\""), Scalar::Boolean(true));
assert_eq!(eval("BLANK() == BLANK()"), Scalar::Boolean(true));
assert_eq!(eval("BLANK() == 0"), Scalar::Boolean(false));
assert_eq!(eval("BLANK() == \"\""), Scalar::Boolean(false));
// `=` keeps coercing BLANK, as before.
assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true));
}
#[test]
fn strict_equality_matches_a_decimal_column_against_an_integer_literal() {
// A Decimal column compared with an integer literal compares numerically: `Sales[Amount]` is
// `Scalar::Decimal`, the literal `Scalar::Integer`.
assert_eq!(eval_in_sales("COUNTROWS(FILTER(Sales, Sales[Amount] == 10))"), Scalar::Integer(1));
assert_eq!(eval_in_sales("COUNTROWS(FILTER(Sales, Sales[Region] == \"east\"))"), Scalar::Integer(2));
// `strict_eq` keeps text case-sensitive but joins numeric keys across variants, so a
// relationship whose keys are Integer on one side and Decimal on the other still matches.
assert!(gridcraft_dax::Scalar::Integer(2).strict_eq(&Scalar::Decimal(2.0)));
assert!(!gridcraft_dax::Scalar::Integer(2).strict_eq(&Scalar::Decimal(2.5)));
assert!(!Scalar::String("a".into()).strict_eq(&Scalar::String("A".into())));
// Beyond 2^53 two integers share an `f64`, and they must stay distinct keys.
assert!(!Scalar::Integer(9_007_199_254_740_992).strict_eq(&Scalar::Integer(9_007_199_254_740_993)));
// A large key still matches itself, in the same variant and through currency.
assert!(Scalar::Integer(9_007_199_254_740_993).strict_eq(&Scalar::Integer(9_007_199_254_740_993)));
assert!(Scalar::Currency(9_007_199_254_740_993).strict_eq(&Scalar::Currency(9_007_199_254_740_993)));
// `compare` keeps the same exactness, so `IN` and `=` do not conflate large integers either.
assert_eq!(Scalar::Integer(9_007_199_254_740_992).compare(&Scalar::Integer(9_007_199_254_740_993)), Some(std::cmp::Ordering::Less));
assert!(Scalar::Integer(9_007_199_254_740_993).compare(&Scalar::Integer(9_007_199_254_740_993)) == Some(std::cmp::Ordering::Equal));
// A large integer against an integral decimal stays exact instead of rounding into it.
assert_eq!(Scalar::Integer(9_007_199_254_740_993).compare(&Scalar::Decimal(9_007_199_254_740_992.0)), Some(std::cmp::Ordering::Greater));
}
#[test]
fn calculate_applies_removal_modifiers_before_its_filters() {
// `ALL(Sales)` clears the outer context first, whatever its position, and the explicit filters
// then apply: both argument orders leave the Region filter in force.
assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), Sales[Region] = \"East\", ALL(Sales))"), Scalar::Integer(2));
assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), ALL(Sales), Sales[Region] = \"East\")"), Scalar::Integer(2));
// ALL on a column clears only that column, so the Amount filter survives.
assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), Sales[Amount] = 10, ALL(Sales[Region]))"), Scalar::Integer(1));
}
-864
View File
@@ -1,864 +0,0 @@
//! Evaluator tests for the non-metadata information functions.
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
use gridcraft_dax::value::{Scalar, ScalarKey, TableValue};
use gridcraft_dax::{Binder, Evaluator, FilterContext, parse_expression};
fn model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Product".into(),
columns: vec![
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
ModelColumn { name: "Color".into(), data_type: Some("String".into()) },
ModelColumn { name: "Category".into(), data_type: Some("String".into()) },
ModelColumn { name: "Price".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Cost".into(), data_type: Some("Currency".into()) },
ModelColumn { name: "Active".into(), data_type: Some("Boolean".into()) },
ModelColumn { name: "LaunchDate".into(), data_type: Some("DateTime".into()) },
],
rows: vec![
vec![
Scalar::Integer(1),
Scalar::String("Wireless Headphones".into()),
Scalar::String("Red".into()),
Scalar::String("Audio".into()),
Scalar::Decimal(20.0),
Scalar::Currency(150_000),
Scalar::Boolean(true),
Scalar::DateTime(45292.0),
],
vec![
Scalar::Integer(2),
Scalar::String("Red Widget".into()),
Scalar::String("Red".into()),
Scalar::String("Audio".into()),
Scalar::Decimal(30.5),
Scalar::Currency(200_000),
Scalar::Boolean(true),
Scalar::DateTime(45300.0),
],
vec![
Scalar::Integer(3),
Scalar::String("Blue Gadget".into()),
Scalar::String("Blue".into()),
Scalar::String("Computers".into()),
Scalar::Decimal(10.0),
Scalar::Currency(50_000),
Scalar::Boolean(false),
Scalar::DateTime(45310.0),
],
vec![
Scalar::Integer(4),
Scalar::String("Noise Cancel Headphones".into()),
Scalar::String("Blue".into()),
Scalar::String("Audio".into()),
Scalar::Decimal(40.0),
Scalar::Currency(300_000),
Scalar::Boolean(true),
Scalar::DateTime(45320.0),
],
],
},
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
],
rows: vec![
vec![Scalar::String("East".into()), Scalar::Decimal(10.0), Scalar::Integer(2), Scalar::Integer(1)],
vec![Scalar::String("West".into()), Scalar::Decimal(20.0), Scalar::Integer(3), Scalar::Integer(2)],
vec![Scalar::String("East".into()), Scalar::Decimal(30.0), Scalar::Integer(4), Scalar::Integer(1)],
],
},
ModelTable {
name: "EmptyStats".into(),
columns: vec![ModelColumn { name: "Empty Value".into(), data_type: Some("String".into()) }],
rows: vec![],
},
],
relationships: vec![Relationship {
from_table: "Sales".into(),
from_column: "ProductKey".into(),
to_table: "Product".into(),
to_column: "ProductKey".into(),
bidirectional: false,
inactive: false,
}],
measures: vec![
Measure {
name: "Total Sales".into(),
formula: "SUM(Sales[Amount])".into(),
table: Some("Sales".into()),
format: Some("#,0.00".into()),
expr: None,
},
Measure { name: "Total Quantity".into(), formula: "SUM(Sales[Quantity])".into(), table: Some("Sales".into()), format: None, expr: None },
],
};
model.parse_formulas().expect("fixture model parses");
model
}
fn eval(src: &str) -> Result<Scalar, String> {
evaluate(src, FilterContext::default())
}
fn eval_with(src: &str, build_filters: impl FnOnce(&DataModel) -> FilterContext) -> Result<Scalar, String> {
let model = model();
let filters = build_filters(&model);
evaluate_with_model(&model, src, filters)
}
fn evaluate(src: &str, filters: FilterContext) -> Result<Scalar, String> {
let model = model();
evaluate_with_model(&model, src, filters)
}
fn evaluate_with_model(model: &DataModel, src: &str, filters: FilterContext) -> Result<Scalar, String> {
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
let expr = parse_expression(src).map_err(|error| error.to_string())?;
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate_with(&bound, filters).map_err(|error| error.message)
}
fn eval_table(src: &str) -> Result<TableValue, String> {
let model = model();
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
let expr = parse_expression(src).map_err(|error| error.to_string())?;
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate_table(&bound).map_err(|error| error.message)
}
fn number(src: &str) -> f64 {
match eval(src) {
Ok(value) => value.to_number().unwrap_or_else(|| panic!("`{src}` did not evaluate to a number: {value:?}")),
Err(error) => panic!("`{src}` failed: {error}"),
}
}
fn boolean(src: &str) -> bool {
match eval(src) {
Ok(Scalar::Boolean(value)) => value,
other => panic!("`{src}` did not evaluate to a Boolean: {other:?}"),
}
}
fn error_message(src: &str) -> String {
match eval(src) {
Ok(value) => panic!("`{src}` should fail, got {value:?}"),
Err(message) => message,
}
}
fn filter(model: &DataModel, table: &str, column: &str, values: &[Scalar]) -> FilterContext {
let mut filters = FilterContext::default();
let table = model.table_index(table).expect("table exists");
let column = model.column_index(table, column).expect("column exists");
filters.set(table, column, values.iter().map(ScalarKey::from));
filters
}
#[test]
fn column_statistics_reports_every_column() {
let table = eval_table("COLUMNSTATISTICS()").expect("column statistics");
let names: Vec<&str> = table.columns.iter().map(|column| column.name.as_str()).collect();
assert_eq!(names, ["Table Name", "Column Name", "Min", "Max", "Cardinality", "Max Length"]);
// Product has 8 columns, Sales has 4 and EmptyStats has 1.
assert_eq!(table.rows.len(), 13);
let row = table
.rows
.iter()
.find(|row| row[0] == Scalar::String("Product".into()) && row[1] == Scalar::String("Name".into()))
.expect("Product[Name] row");
assert_eq!(row[2], Scalar::String("Blue Gadget".into()));
assert_eq!(row[3], Scalar::String("Wireless Headphones".into()));
assert_eq!(row[4], Scalar::Integer(4));
assert_eq!(row[5], Scalar::Integer(23));
let price = table
.rows
.iter()
.find(|row| row[0] == Scalar::String("Product".into()) && row[1] == Scalar::String("Price".into()))
.expect("Product[Price] row");
assert_eq!(price[2], Scalar::Decimal(10.0));
assert_eq!(price[3], Scalar::Decimal(40.0));
assert_eq!(price[4], Scalar::Integer(4));
assert_eq!(price[5], Scalar::Blank);
let empty = table.rows.iter().find(|row| row[0] == Scalar::String("EmptyStats".into())).expect("EmptyStats row");
assert_eq!(empty[2], Scalar::Blank);
assert_eq!(empty[3], Scalar::Blank);
assert_eq!(empty[4], Scalar::Integer(0));
assert_eq!(empty[5], Scalar::Blank);
}
#[test]
fn contains_and_containsrow() {
assert!(boolean("CONTAINS(Product, Product[Color], \"Red\")"));
assert!(boolean("CONTAINS(Product, Product[Color], \"Red\", Product[Category], \"Audio\")"));
assert!(!boolean("CONTAINS(Product, Product[Color], \"Red\", Product[Category], \"Computers\")"));
// Strict equality: BLANK does not match the number 0.
assert!(!boolean("CONTAINS(Product, Product[Color], BLANK())"));
assert!(boolean("EVALUATEANDLOG(CONTAINS(Product, Product[ProductKey], 3))"));
assert!(error_message("CONTAINS(Product, Product[Color], \"Red\", Product[Name])").contains("column/value pairs"));
assert!(boolean("CONTAINSROW({1, 2}, 2)"));
assert!(!boolean("CONTAINSROW({1, 2}, 3)"));
// One value per table column: `Sales` is (Region, Amount, Quantity, ProductKey).
assert!(boolean("CONTAINSROW(Sales, \"East\", 10.0, 2, 1)"));
assert!(!boolean("CONTAINSROW(Sales, \"West\", 10.0, 2, 1)"));
// A value count that is not the column count is an error, never a prefix match.
assert!(error_message("CONTAINSROW(Sales, \"East\")").contains("one value"));
assert!(error_message("CONTAINSROW({1}, 1, 2)").contains("one value"));
}
#[test]
fn contains_string_variants() {
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"ell\")"));
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"WORLD\")"));
assert!(!boolean("CONTAINSSTRING(\"Hello World\", \"xyz\")"));
// Excel wildcards: `?` one character, `*` any run, `~` escapes a wildcard.
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"W?rld\")"));
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"H*d\")"));
assert!(boolean("CONTAINSSTRING(\"a*b\", \"~*\")"));
assert!(!boolean("CONTAINSSTRING(\"abc\", \"~*\")"));
assert!(boolean("CONTAINSSTRING(BLANK(), \"\")"));
assert!(boolean("CONTAINSSTRINGEXACT(\"Hello World\", \"World\")"));
assert!(!boolean("CONTAINSSTRINGEXACT(\"Hello World\", \"world\")"));
// Exact matching does not interpret wildcards.
assert!(boolean("CONTAINSSTRINGEXACT(\"a*b\", \"*\")"));
assert!(!boolean("CONTAINSSTRINGEXACT(\"Hello\", \"Ell\")"));
}
#[test]
fn user_and_connection_functions_return_defaults() {
assert_eq!(eval("CUSTOMDATA()"), Ok(Scalar::String(String::new())));
assert_eq!(eval("USERCULTURE()"), Ok(Scalar::String("en-US".into())));
assert_eq!(eval("USEROBJECTID()"), Ok(Scalar::String(String::new())));
// USERNAME is the `DOMAIN\user` identity; USERPRINCIPALNAME is the `user@domain` directory
// principal. On a test host without a user both are empty.
let host_user = std::env::var("USERNAME").or_else(|_| std::env::var("USER")).unwrap_or_default();
let username = match std::env::var("USERDOMAIN") {
Ok(domain) if !domain.is_empty() && !host_user.is_empty() => format!("{domain}\\{host_user}"),
_ => host_user.clone(),
};
let principal = match (
std::env::var("USERDNSDOMAIN").ok().filter(|domain| !domain.is_empty()),
std::env::var("USERDOMAIN").ok().filter(|domain| !domain.is_empty()),
host_user.as_str(),
) {
(_, _, "") => host_user,
(Some(domain), _, user) | (None, Some(domain), user) => format!("{user}@{}", domain.to_ascii_lowercase()),
(None, None, user) => user.to_string(),
};
assert_eq!(eval("USERNAME()"), Ok(Scalar::String(username)));
assert_eq!(eval("USERPRINCIPALNAME()"), Ok(Scalar::String(principal)));
// The principal name is the `user@domain` form, never the `DOMAIN\user` form.
assert!(!matches!(eval("USERPRINCIPALNAME()"), Ok(Scalar::String(value)) if value.contains('\\')));
}
#[test]
fn evaluate_and_log_returns_its_argument() {
assert_eq!(eval("EVALUATEANDLOG(42)"), Ok(Scalar::Integer(42)));
assert_eq!(eval("EVALUATEANDLOG(7, \"label\", 5)"), Ok(Scalar::Integer(7)));
let table = eval_table("EVALUATEANDLOG(Sales)").expect("logged table");
assert_eq!(table.rows.len(), 3);
assert_eq!(table.columns.len(), 4);
assert!(eval("EVALUATEANDLOG()").is_err());
}
#[test]
fn filter_context_predicates() {
assert!(!boolean("HASONEVALUE(Product[Color])"));
assert!(!boolean("HASONEVALUE(Product[Category])"));
let single_category =
eval_with("HASONEVALUE(Product[Category])", |model| filter(model, "Product", "Category", &[Scalar::String("Audio".into())]))
.expect("HASONEVALUE");
assert_eq!(single_category, Scalar::Boolean(true));
let two_colors = eval_with("HASONEVALUE(Product[Color])", |model| {
filter(model, "Product", "Color", &[Scalar::String("Red".into()), Scalar::String("Blue".into())])
})
.expect("HASONEVALUE with two values");
assert_eq!(two_colors, Scalar::Boolean(false));
let single_color_filter =
eval_with("HASONEFILTER(Product[Color])", |model| filter(model, "Product", "Color", &[Scalar::String("Red".into())])).expect("HASONEFILTER");
assert_eq!(single_color_filter, Scalar::Boolean(true));
let propagated = eval_with("HASONEFILTER(Product[Color])", |model| filter(model, "Product", "Category", &[Scalar::String("Computers".into())]))
.expect("HASONEFILTER ignores propagated filters");
assert_eq!(propagated, Scalar::Boolean(false));
let two_value_filter = eval_with("HASONEFILTER(Product[Color])", |model| {
filter(model, "Product", "Color", &[Scalar::String("Red".into()), Scalar::String("Blue".into())])
})
.expect("HASONEFILTER with two values");
assert_eq!(two_value_filter, Scalar::Boolean(false));
let empty_column = eval("HASONEVALUE(EmptyStats[Empty Value])").expect("empty column");
assert_eq!(empty_column, Scalar::Boolean(false));
assert!(!boolean("ISFILTERED(Product[Color])"));
let filtered =
eval_with("ISFILTERED(Product[Color])", |model| filter(model, "Product", "Color", &[Scalar::String("Red".into())])).expect("ISFILTERED");
assert_eq!(filtered, Scalar::Boolean(true));
let unrelated = eval_with("ISFILTERED(Product[Name])", |model| filter(model, "Product", "Color", &[Scalar::String("Red".into())]))
.expect("ISFILTERED other column");
assert_eq!(unrelated, Scalar::Boolean(false));
}
#[test]
fn cross_filtered_follows_relationship_propagation() {
assert!(!boolean("ISCROSSFILTERED(Sales)"));
assert!(!boolean("ISCROSSFILTERED(Product)"));
let from_dimension = |model: &DataModel| filter(model, "Product", "Category", &[Scalar::String("Audio".into())]);
assert_eq!(eval_with("ISCROSSFILTERED(Sales)", from_dimension).expect("sales"), Scalar::Boolean(true));
assert_eq!(eval_with("ISCROSSFILTERED(Sales[Amount])", from_dimension).expect("sales column"), Scalar::Boolean(true));
assert_eq!(eval_with("ISCROSSFILTERED(Product)", from_dimension).expect("product"), Scalar::Boolean(true));
// Filtering the many-side fact table does not propagate to the one-side dimension.
let from_fact = |model: &DataModel| filter(model, "Sales", "Region", &[Scalar::String("East".into())]);
assert_eq!(eval_with("ISCROSSFILTERED(Product)", from_fact).expect("product"), Scalar::Boolean(false));
assert_eq!(eval_with("ISCROSSFILTERED(Sales)", from_fact).expect("sales"), Scalar::Boolean(true));
}
/// `Sales -> Product -> Category`, plus an inactive `Product -> AltCategory` link so
/// `USERELATIONSHIP` can switch a hop on.
fn snowflake_model() -> DataModel {
let mut model = DataModel {
tables: vec![
ModelTable {
name: "Category".into(),
columns: vec![
ModelColumn { name: "CategoryKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
],
rows: vec![vec![Scalar::Integer(1), Scalar::String("Audio".into())], vec![Scalar::Integer(2), Scalar::String("Computers".into())]],
},
ModelTable {
name: "AltCategory".into(),
columns: vec![
ModelColumn { name: "CategoryKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
],
rows: vec![vec![Scalar::Integer(1), Scalar::String("Audio".into())], vec![Scalar::Integer(2), Scalar::String("Computers".into())]],
},
ModelTable {
name: "Product".into(),
columns: vec![
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "CategoryKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "AltCategoryKey".into(), data_type: Some("Int64".into()) },
],
rows: vec![
vec![Scalar::Integer(1), Scalar::Integer(1), Scalar::Integer(1)],
vec![Scalar::Integer(2), Scalar::Integer(1), Scalar::Integer(2)],
vec![Scalar::Integer(3), Scalar::Integer(2), Scalar::Integer(1)],
],
},
ModelTable {
name: "Sales".into(),
columns: vec![
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
],
rows: vec![
vec![Scalar::Integer(1), Scalar::Decimal(10.0)],
vec![Scalar::Integer(2), Scalar::Decimal(20.0)],
vec![Scalar::Integer(3), Scalar::Decimal(30.0)],
],
},
],
relationships: vec![
Relationship {
from_table: "Sales".into(),
from_column: "ProductKey".into(),
to_table: "Product".into(),
to_column: "ProductKey".into(),
bidirectional: false,
inactive: false,
},
Relationship {
from_table: "Product".into(),
from_column: "CategoryKey".into(),
to_table: "Category".into(),
to_column: "CategoryKey".into(),
bidirectional: false,
inactive: false,
},
Relationship {
from_table: "Product".into(),
from_column: "AltCategoryKey".into(),
to_table: "AltCategory".into(),
to_column: "CategoryKey".into(),
bidirectional: false,
inactive: true,
},
],
measures: vec![],
};
model.parse_formulas().expect("fixture model parses");
model
}
#[test]
fn cross_filtered_follows_the_whole_chain_and_relationship_overrides() {
let model = snowflake_model();
let with = |filters: FilterContext, src: &str| evaluate_with_model(&model, src, filters);
assert_eq!(with(FilterContext::default(), "ISCROSSFILTERED(Sales)").expect("unfiltered sales"), Scalar::Boolean(false));
assert_eq!(with(FilterContext::default(), "ISCROSSFILTERED(Product)").expect("unfiltered product"), Scalar::Boolean(false));
// Two hops away: `Category -> Product -> Sales`. A single-hop check misses this.
let category = filter(&model, "Category", "Name", &[Scalar::String("Audio".into())]);
assert_eq!(with(category.clone(), "ISCROSSFILTERED(Sales)").expect("sales"), Scalar::Boolean(true));
assert_eq!(with(category.clone(), "ISCROSSFILTERED(Product)").expect("product"), Scalar::Boolean(true));
assert_eq!(with(category.clone(), "ISCROSSFILTERED(Category)").expect("category"), Scalar::Boolean(true));
// The chain only runs towards the many side; the inactive branch stays out of it.
assert_eq!(with(category.clone(), "ISCROSSFILTERED(AltCategory)").expect("alt category"), Scalar::Boolean(false));
// A filter on the fact table does not climb the one-way chain towards `Category`.
let sales = filter(&model, "Sales", "Amount", &[Scalar::Decimal(10.0)]);
assert_eq!(with(sales.clone(), "ISCROSSFILTERED(Category)").expect("category"), Scalar::Boolean(false));
assert_eq!(with(sales.clone(), "ISCROSSFILTERED(Sales)").expect("sales"), Scalar::Boolean(true));
// An inactive relationship is ignored until `USERELATIONSHIP` activates it; the override in
// the filter context, not the model's `inactive` flag, must decide.
let alt_category = filter(&model, "AltCategory", "Name", &[Scalar::String("Audio".into())]);
assert_eq!(with(alt_category.clone(), "ISCROSSFILTERED(Sales)").expect("inactive link"), Scalar::Boolean(false));
let activation = "CALCULATE(ISCROSSFILTERED(Sales), USERELATIONSHIP(Product[AltCategoryKey], AltCategory[CategoryKey]))";
assert_eq!(with(alt_category.clone(), activation).expect("activated link"), Scalar::Boolean(true));
// Activating the other pair leaves the `Category` chain alone.
assert_eq!(with(alt_category, "ISCROSSFILTERED(Category)").expect("category"), Scalar::Boolean(false));
// `CROSSFILTER` widens the fact-side filter back to the dimension for the surrounding
// CALCULATE only.
let widened = "CALCULATE(ISCROSSFILTERED(Product), CROSSFILTER(Sales[ProductKey], Product[ProductKey], BOTH))";
assert_eq!(with(sales, widened).expect("bidirectional override"), Scalar::Boolean(true));
}
#[test]
fn scope_and_subtotal_predicates() {
// Outside a `SUMMARIZE` group no column is in scope, and a row iterator's row context does
// not put one there either: scope is the group-by set of the group being evaluated.
assert!(!boolean("ISINSCOPE(Product[Color])"));
assert_eq!(number("SUMX(Product, IF(ISINSCOPE(Product[Color]), 1, 0))"), 0.0);
assert_eq!(number("SUMX(Sales, IF(ISINSCOPE(Product[Color]), 1, 0))"), 0.0);
}
#[test]
fn is_empty_checks_result_rows() {
assert!(!boolean("ISEMPTY(Sales)"));
assert!(boolean("ISEMPTY(FILTER(Sales, Sales[Amount] > 1000))"));
assert!(boolean("ISEMPTY(EmptyStats)"));
assert!(boolean("ISEMPTY({})"));
}
#[test]
fn type_predicates_are_strict() {
assert!(boolean("ISBOOLEAN(TRUE)"));
assert!(!boolean("ISBOOLEAN(1)"));
assert!(!boolean("ISBOOLEAN(BLANK())"));
assert!(boolean("ISSTRING(\"text\")"));
assert!(!boolean("ISSTRING(1)"));
assert!(!boolean("ISSTRING(BLANK())"));
assert!(boolean("ISINT64(1)"));
assert!(!boolean("ISINT64(1.5)"));
assert!(!boolean("ISDECIMAL(1.5)"));
assert!(boolean("ISDOUBLE(1.5)"));
assert!(!boolean("ISDOUBLE(1)"));
assert!(boolean("ISDATETIME(DATE(2024, 1, 1))"));
assert!(!boolean("ISDATETIME(1)"));
assert!(boolean("ISNUMERIC(1)"));
assert!(boolean("ISNUMERIC(1.5)"));
assert!(!boolean("ISNUMERIC(\"1\")"));
assert!(!boolean("ISNUMERIC(TRUE)"));
assert!(!boolean("ISNUMERIC(DATE(2024, 1, 1))"));
// Column values in a row context keep their storage types.
assert_eq!(number("SUMX(Product, IF(ISDECIMAL(Product[Cost]), 1, 0))"), 4.0);
assert_eq!(number("SUMX(Product, IF(ISDOUBLE(Product[Price]), 1, 0))"), 4.0);
assert_eq!(number("SUMX(Product, IF(ISDOUBLE(Product[Cost]), 1, 0))"), 0.0);
assert_eq!(number("SUMX(Product, IF(ISINT64(Product[ProductKey]), 1, 0))"), 4.0);
assert_eq!(number("SUMX(Product, IF(ISNUMERIC(Product[Cost]), 1, 0))"), 4.0);
assert_eq!(number("SUMX(Product, IF(ISNUMERIC(Product[Active]), 1, 0))"), 0.0);
assert_eq!(number("SUMX(Product, IF(ISDATETIME(Product[LaunchDate]), 1, 0))"), 4.0);
assert_eq!(number("SUMX(Product, IF(ISSTRING(Product[Name]), 1, 0))"), 4.0);
assert_eq!(number("SUMX(Product, IF(ISBOOLEAN(Product[Active]), 1, 0))"), 4.0);
}
#[test]
fn isafter_and_isonorafter_compare_groups() {
assert!(boolean("ISAFTER(2, 1)"));
assert!(!boolean("ISAFTER(1, 1)"));
assert!(!boolean("ISAFTER(1, 2)"));
assert!(boolean("ISAFTER(1, 2, FALSE)"));
assert!(boolean("ISAFTER(1, 2, 0)"));
assert!(boolean("ISAFTER(\"b\", \"A\")"));
// The first differing pair decides; equal pairs fall through to the next group.
assert!(boolean("ISAFTER(1, 1, TRUE, 5, 4)"));
assert!(!boolean("ISAFTER(1, 1, TRUE, 4, 5)"));
// BLANK sorts before every value, including the empty string.
assert!(boolean("ISAFTER(\"\", BLANK())"));
assert!(!boolean("ISAFTER(BLANK(), \"\")"));
assert!(error_message("ISAFTER(\"abc\", 1)").contains("cannot compare"));
assert!(boolean("ISONORAFTER(2, 1)"));
assert!(boolean("ISONORAFTER(1, 1)"));
assert!(!boolean("ISONORAFTER(0, 1)"));
assert!(boolean("ISONORAFTER(1, 2, FALSE)"));
assert!(!boolean("ISONORAFTER(1, 1, TRUE, 4, 5)"));
assert!(boolean("ISONORAFTER(1, 1, TRUE, 5, 4)"));
assert!(!boolean("ISONORAFTER(BLANK(), \"\")"));
assert!(eval("ISONORAFTER(1)").is_err());
}
#[test]
fn selected_measure_functions_require_a_calculation_item() {
assert!(!boolean("ISSELECTEDMEASURE([Total Sales])"));
assert!(!boolean("ISSELECTEDMEASURE([Total Sales], [Total Quantity])"));
assert!(error_message("SELECTEDMEASURE()").contains("selected measure"));
assert!(error_message("SELECTEDMEASURENAME()").contains("selected measure"));
assert!(error_message("SELECTEDMEASUREFORMATSTRING()").contains("selected measure"));
}
#[test]
fn nameof_formats_and_escapes_names() {
assert_eq!(eval("NAMEOF(Sales[Amount])"), Ok(Scalar::String("'Sales'[Amount]".into())));
assert_eq!(eval("NAMEOF([Total Sales])"), Ok(Scalar::String("'Sales'[Total Sales]".into())));
assert_eq!(eval("NAMEOF(Sales)"), Ok(Scalar::String("'Sales'".into())));
assert_eq!(eval("NAMEOF(Sales[Amount], \"TABLE\")"), Ok(Scalar::String("'Sales'".into())));
assert_eq!(eval("NAMEOF([Total Sales], \"PARENT\")"), Ok(Scalar::String("'Sales'".into())));
assert_eq!(eval("NAMEOF(Product[Name], \"SELF\")"), Ok(Scalar::String("[Name]".into())));
assert_eq!(eval("NAMEOF(Sales[Amount], \"COLUMN\")"), Ok(Scalar::String("[Amount]".into())));
assert_eq!(eval("NAMEOF([Total Sales], \"MEASURE\")"), Ok(Scalar::String("[Total Sales]".into())));
assert_eq!(eval("NAMEOF(Sales, \"FULL\", \"UNESCAPED\")"), Ok(Scalar::String("Sales".into())));
assert_eq!(eval("NAMEOF(Product[Name], \"SELF\", \"UNESCAPED\")"), Ok(Scalar::String("Name".into())));
assert_eq!(eval("NAMEOF(Product[Name], \"FULL\", \"MINIMALLYESCAPED\")"), Ok(Scalar::String("Product[Name]".into())));
assert_eq!(eval("NAMEOF([Total Sales], \"SELF\", \"MINIMALLYESCAPED\")"), Ok(Scalar::String("[Total Sales]".into())));
assert!(error_message("NAMEOF(Sales[Amount], \"FULL\", \"UNESCAPED\")").contains("fully qualified"));
assert!(error_message("NAMEOF(Sales, \"PARENT\")").contains("no parent"));
assert!(error_message("NAMEOF(Sales[Amount], \"CALENDAR\")").contains("no calendar"));
assert!(error_message("NAMEOF(Sales[Amount], \"BOGUS\")").contains("does not know component"));
assert!(error_message("NAMEOF(1)").contains("table, column or measure"));
}
#[test]
fn tableof_returns_the_containing_table() {
for source in ["TABLEOF(Sales[Amount])", "TABLEOF(Sales)", "TABLEOF([Total Sales])"] {
let table = eval_table(source).expect(source);
assert_eq!(table.rows.len(), 3, "{source}");
assert_eq!(table.columns.len(), 4, "{source}");
}
// Unqualified column names resolve when a single table carries them.
let empty = eval_table("TABLEOF([Empty Value])").expect("TABLEOF empty column");
assert_eq!(empty.rows.len(), 0);
assert_eq!(empty.columns.len(), 1);
}
#[test]
fn text_contains_match_modes() {
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"wireless bluetooth\")))"), 1.0);
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"WIRELESS\")))"), 1.0);
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"zzz\")))"), 0.0);
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"\")))"), 0.0);
// Typo-tolerant matching accepts an edit distance of 1-2 for longer tokens.
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"headphone\", \"FUZZYMATCHING\")))"), 2.0);
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"hedphone\", \"FUZZYMATCHING\")))"), 2.0);
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"headphone\")))"), 0.0);
// Phrase matching requires adjacent tokens in the specified order.
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"noise cancel\", \"PHRASEMATCHING\")))"), 1.0);
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"cancel noise\", \"PHRASEMATCHING\")))"), 0.0);
assert!(error_message("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"x\", \"BOGUS\")))").contains("match mode"));
}
#[test]
fn text_similarity_scores_matches() {
let red = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\"))");
assert!(red > 0.0, "red score {red}");
assert_eq!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"zzz\"))"), 0.0);
assert!((number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"RED\"))") - red).abs() < 1e-12);
let both = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red widget\"))");
assert!(both > red, "a two-term match ({both}) should outrank one term ({red})");
assert!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"hedphone\", \"FUZZYMATCHING\"))") > 0.0);
assert_eq!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"hedphone\"))"), 0.0);
assert!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"noise cancel\", \"PHRASEMATCHING\"))") > 0.0);
assert_eq!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"cancel noise\", \"PHRASEMATCHING\"))"), 0.0);
let blank = number("MAXX(Product, TEXTSIMILARITY(Product[Name], BLANK()))");
assert_eq!(blank, 0.0);
}
#[test]
fn text_similarity_scores_each_row_against_the_shared_corpus() {
// `MAXX` evaluates `TEXTSIMILARITY` once per row, and every one of those calls ranks against
// the same column corpus (4 documents, 9 tokens, `red` in one document). The statistics are
// memoised, so the row that matches must score exactly as it does on its own.
let score = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\"))");
// k1 = 1.2, b = 0.75: idf = ln(1 + (4 - 1 + 0.5) / (1 + 0.5)); the target has two tokens and
// the corpus averages 9 / 4 = 2.25, so the denominator is 1 + 1.2 * (0.25 + 0.75 * 2 / 2.25).
assert!((score - 1.261_304_842_627_171_4).abs() < 1e-9, "unexpected score {score}");
// The same row scored through its own filter context gets the same value.
let scoped = evaluate("TEXTSIMILARITY(Product[Name], \"red\")", filter(&model(), "Product", "Name", &[Scalar::String("Red Widget".into())]))
.expect("scoped score");
assert_eq!(scoped, Scalar::Decimal(score));
}
#[test]
fn text_similarity_reports_an_oversized_column_instead_of_rescoring() {
// Beyond the text work budget the function must fail: substituting a cheaper corpus would
// silently change every score for the same column.
let mut model = DataModel {
tables: vec![ModelTable {
name: "Notes".into(),
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
rows: (0..1500).map(|index| vec![Scalar::String(format!("note {index} {}", "x".repeat(1000)))]).collect(),
}],
relationships: vec![],
measures: vec![],
};
model.parse_formulas().expect("fixture model parses");
let error = evaluate_with_model(&model, "MAXX(Notes, TEXTSIMILARITY(Notes[Text], \"note\"))", FilterContext::default())
.expect_err("a column beyond the work budget");
assert!(error.contains("too large"), "unexpected error: {error}");
}
/// A one-column model whose rows are the given texts.
fn corpus_model(documents: [&str; 3]) -> DataModel {
let mut model = DataModel {
tables: vec![ModelTable {
name: "NoteLines".into(),
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
rows: documents.iter().map(|document| vec![Scalar::String((*document).into())]).collect(),
}],
relationships: vec![],
measures: vec![],
};
model.parse_formulas().expect("fixture model parses");
model
}
#[test]
fn text_similarity_keeps_each_model_s_corpus() {
// The two corpora have the same shape, the same first row and the same last row; only the
// middle document differs. Statistics memoised on anything weaker than the model itself would
// score the second corpus with the first one's document frequencies.
let dense = corpus_model(["red alpha", "red beta", "same tail"]);
let sparse = corpus_model(["red alpha", "blue beta", "same tail"]);
let score =
|model: &DataModel| match evaluate_with_model(model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
Ok(Scalar::Decimal(value)) => value,
other => panic!("unexpected result: {other:?}"),
};
let dense_score = score(&dense);
let sparse_score = score(&sparse);
// `red` is in two of the three documents above and in one of them below, so it is rarer and
// scores higher.
assert!(dense_score > 0.0, "dense score {dense_score}");
assert!(sparse_score > dense_score, "sparse {sparse_score} should outrank dense {dense_score}");
}
#[test]
fn text_similarity_sees_an_edited_corpus() {
// The model address and row count stay the same when a caller edits a text cell, so the memo
// must be invalidated by the corpus fingerprint rather than by those two facts alone.
let mut model = corpus_model(["red alpha", "blue beta", "same tail"]);
let score =
|model: &DataModel| match evaluate_with_model(model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
Ok(Scalar::Decimal(value)) => value,
other => panic!("unexpected result: {other:?}"),
};
let rare = score(&model);
model.tables[0].rows[1][0] = Scalar::String("red beta".into());
// `red` now occurs in two of the three documents, so it is less distinctive and scores lower.
let common = score(&model);
assert!(rare > 0.0, "rare score {rare}");
assert!(common < rare, "edited corpus {common} should score below {rare}");
}
#[test]
fn text_similarity_does_not_alias_between_interleaved_evaluators() {
// Two models scored alternately on one thread: the memo must never answer one corpus's
// statistics for the other, in either order and across repeated evaluations.
let dense = corpus_model(["red alpha", "red beta", "same tail"]);
let sparse = corpus_model(["red alpha", "blue beta", "same tail"]);
let score =
|model: &DataModel| match evaluate_with_model(model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
Ok(Scalar::Decimal(value)) => value,
other => panic!("unexpected result: {other:?}"),
};
let dense_first = score(&dense);
let sparse_first = score(&sparse);
assert!(sparse_first > dense_first, "sparse {sparse_first} should outrank dense {dense_first}");
for _ in 0..3 {
assert_eq!(score(&dense), dense_first, "dense score changed between evaluations");
assert_eq!(score(&sparse), sparse_first, "sparse score changed between evaluations");
}
}
#[test]
fn text_similarity_error_leaves_no_stale_statistics() {
// A call that fails on the work budget must not leave statistics behind for the next call.
let mut oversized = DataModel {
tables: vec![ModelTable {
name: "Notes".into(),
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
rows: (0..1500).map(|index| vec![Scalar::String(format!("note {index} {}", "x".repeat(1000)))]).collect(),
}],
relationships: vec![],
measures: vec![],
};
oversized.parse_formulas().expect("fixture model parses");
let error = evaluate_with_model(&oversized, "MAXX(Notes, TEXTSIMILARITY(Notes[Text], \"note\"))", FilterContext::default())
.expect_err("a column beyond the work budget");
assert!(error.contains("too large"), "unexpected error: {error}");
// The normal corpus still scores exactly as it does on its own.
let model = corpus_model(["red alpha", "blue beta", "same tail"]);
let score = match evaluate_with_model(&model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
Ok(Scalar::Decimal(value)) => value,
other => panic!("unexpected result: {other:?}"),
};
let sparse = corpus_model(["red alpha", "blue beta", "same tail"]);
let expected = match evaluate_with_model(&sparse, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
Ok(Scalar::Decimal(value)) => value,
other => panic!("unexpected result: {other:?}"),
};
assert_eq!(score, expected);
}
#[test]
fn text_similarity_counts_numeric_text_exactly() {
// 70,000 one-digit integers are 70,000 characters of text, not twenty each: a per-variant bound
// that assumed twenty would reject this column although its text is tiny. The query is three
// characters, so the old bound would have asked for 4.2 M characters.
let mut model = DataModel {
tables: vec![ModelTable {
name: "Counts".into(),
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
rows: (0..70_000).map(|_| vec![Scalar::Integer(1)]).collect(),
}],
relationships: vec![],
measures: vec![],
};
model.parse_formulas().expect("fixture model parses");
let score = evaluate_with_model(&model, "MAXX(Counts, TEXTSIMILARITY(Counts[Value], \"one\"))", FilterContext::default());
assert!(matches!(score, Ok(Scalar::Decimal(_))), "unexpected result: {score:?}");
}
#[test]
fn text_similarity_rejects_a_column_whose_text_exceeds_the_budget() {
// A large decimal formats to hundreds of characters, so a column of them must be rejected even
// though the value count alone looks harmless.
let mut model = DataModel {
tables: vec![ModelTable {
name: "Wide".into(),
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Double".into()) }],
rows: (0..20_000).map(|_| vec![Scalar::Decimal(1e308)]).collect(),
}],
relationships: vec![],
measures: vec![],
};
model.parse_formulas().expect("fixture model parses");
let error = evaluate_with_model(&model, "MAXX(Wide, TEXTSIMILARITY(Wide[Value], \"1\"))", FilterContext::default())
.expect_err("a column whose text exceeds the budget");
assert!(error.contains("too large"), "unexpected error: {error}");
}
#[test]
fn text_similarity_keeps_two_queries_apart_in_one_evaluation() {
// Both queries run inside one evaluation, so they hit the same memo: each must get the
// statistics for its own terms.
let combined = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\")) + MAXX(Product, TEXTSIMILARITY(Product[Name], \"widget\"))");
let red = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\"))");
let widget = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"widget\"))");
assert!(red > 0.0 && widget > 0.0);
assert!((combined - (red + widget)).abs() < 1e-9, "combined {combined} should be {red} + {widget}");
}
#[test]
fn distinct_values_fold_text_case() {
// `"East"` and `"east"` are one distinct value under the model collation, so `HASONEVALUE`
// agrees with `VALUES`/`DISTINCTCOUNT` and `COLUMNSTATISTICS` reports the same cardinality.
let mut model = DataModel {
tables: vec![ModelTable {
name: "Regions".into(),
columns: vec![ModelColumn { name: "Name".into(), data_type: Some("String".into()) }],
rows: vec![vec![Scalar::String("East".into())], vec![Scalar::String("east".into())]],
}],
relationships: vec![],
measures: vec![],
};
model.parse_formulas().expect("fixture model parses");
let one_value = evaluate_with_model(&model, "HASONEVALUE(Regions[Name])", FilterContext::default()).expect("has one value");
assert_eq!(one_value, Scalar::Boolean(true));
let evaluator = Evaluator::new(&model).expect("evaluator");
let expr = parse_expression("COLUMNSTATISTICS()").expect("parse");
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
let table = evaluator.evaluate_table(&bound).expect("column statistics");
let row = table
.rows
.iter()
.find(|row| row[0] == Scalar::String("Regions".into()) && row[1] == Scalar::String("Name".into()))
.expect("Regions[Name] row");
assert_eq!(row[4], Scalar::Integer(1), "Cardinality must fold text case");
}
#[test]
fn isafter_keeps_value_pairs_that_look_like_order_flags() {
// `0` and `1` are the documented `Order` shorthands, but here they are the second pair's
// values: the first pair is equal, so the second one decides.
assert!(!boolean("ISAFTER(1, 1, 0, 1)"), "0 < 1, so the pair is not after");
assert!(boolean("ISAFTER(1, 1, 2, 1)"), "2 > 1, so the pair is after");
// ISONORAFTER also includes equality, and the pair here is strictly before.
assert!(!boolean("ISONORAFTER(1, 1, 0, 1)"));
assert!(boolean("ISONORAFTER(1, 1, 1, 1)"));
assert!(boolean("ISONORAFTER(1, 1, 2, 1)"));
}
#[test]
fn isafter_accepts_a_flag_after_every_pair() {
// A flag after each pair must still split into pairs, not into a pair plus a dangling value.
assert!(boolean("ISAFTER(1, 1, TRUE, 2, 3, FALSE)"));
assert!(boolean("ISAFTER(1, 1, TRUE, 3, 2)"));
assert!(!boolean("ISAFTER(1, 1, TRUE, 2, 3)"));
assert!(boolean("ISONORAFTER(1, 1, TRUE, 2, 2)"));
}
#[test]
fn isafter_rejects_an_odd_argument_count() {
assert!(eval("ISAFTER(1)").is_err());
// `ISAFTER(1, 1, 0)` is a pair plus the `0` shorthand flag, so only a leftover value is an
// error: here the `3` after the second pair is neither a flag nor paired.
assert!(eval("ISONORAFTER(1, 1, 2, 2, 3)").is_err());
}
#[test]
fn isafter_accepts_a_computed_order_flag() {
// A computed `Order` flag is accepted by the pair split and decides the sort direction:
// `TRUE` is ascending, `FALSE` is descending (as in `ISAFTER(1, 2, FALSE)` above). The
// single-evaluation guarantee itself is structural — the cached `Scalar` feeds both the
// split and the direction read, and `flag_direction` takes no evaluator to re-evaluate
// with — so a constant flag cannot observe the evaluation count here.
assert!(!boolean("ISAFTER(1, 2, IF(1 > 0, TRUE, FALSE))"));
assert!(boolean("ISAFTER(2, 1, IF(1 > 0, TRUE, FALSE))"));
assert!(boolean("ISAFTER(1, 2, IF(1 > 0, FALSE, TRUE))"));
assert!(!boolean("ISAFTER(2, 1, IF(1 > 0, FALSE, TRUE))"));
assert!(boolean("ISONORAFTER(1, 1, IF(1 > 0, TRUE, FALSE))"));
assert!(boolean("ISONORAFTER(1, 1, IF(1 > 0, FALSE, TRUE))"));
}
#[test]
fn contains_row_needs_one_value_per_column() {
// `Sales` has four columns: a short value list is an error, not a leading-prefix match.
assert!(eval("CONTAINSROW(Sales, \"East\")").is_err());
assert!(eval("CONTAINSROW(Sales, \"East\", 10.0, 2, 1)").is_ok());
assert!(!boolean("CONTAINSROW(Sales, \"East\", 20.0, 2, 1)"));
}
-72
View File
@@ -1,72 +0,0 @@
//! Evaluator tests for bitwise integer operations and `IF.EAGER`.
use gridcraft_dax::model::DataModel;
use gridcraft_dax::value::Scalar;
use gridcraft_dax::{Binder, Evaluator, parse_expression};
fn model() -> DataModel {
DataModel { tables: vec![], relationships: vec![], measures: vec![] }
}
fn eval_result(source: &str) -> Result<Scalar, String> {
let model = model();
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
let expr = parse_expression(source).map_err(|error| error.to_string())?;
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
evaluator.evaluate(&bound).map_err(|error| error.to_string())
}
fn eval(source: &str) -> Scalar {
eval_result(source).expect("expression evaluates")
}
#[test]
fn bitwise_and_or_xor() {
assert_eq!(eval("BITAND(5, 3)"), Scalar::Integer(1));
assert_eq!(eval("BITAND(13, 25)"), Scalar::Integer(9));
assert_eq!(eval("BITAND(-1, 255)"), Scalar::Integer(255));
assert_eq!(eval("BITAND(3.9, 1)"), Scalar::Integer(1));
assert_eq!(eval("BITOR(5, 3)"), Scalar::Integer(7));
assert_eq!(eval("BITOR(13, 25)"), Scalar::Integer(29));
assert_eq!(eval("BITXOR(5, 3)"), Scalar::Integer(6));
assert_eq!(eval("BITXOR(13, 25)"), Scalar::Integer(20));
assert_eq!(eval("BITXOR(0, 0)"), Scalar::Integer(0));
}
#[test]
fn bitwise_keeps_integers_above_the_f64_precision_limit() {
// 2^53 + 1 is not representable as an `f64`; routing a native Integer through one rounds it
// to 2^53 and drops the low bit. DAX truncates non-integers, so a whole number must stay exact.
assert_eq!(eval("BITAND(9007199254740993, 1)"), Scalar::Integer(1));
assert_eq!(eval("BITOR(9007199254740992, 1)"), Scalar::Integer(9007199254740993));
assert_eq!(eval("BITXOR(9007199254740993, 1)"), Scalar::Integer(9007199254740992));
}
#[test]
fn bitwise_rejects_out_of_range_values() {
assert!(eval_result("BITAND(1e30, 1)").is_err());
assert!(eval_result("BITOR(-1e30, 1)").is_err());
}
#[test]
fn if_eager_selects_a_branch() {
assert_eq!(eval("IF.EAGER(TRUE, 1, 2)"), Scalar::Integer(1));
assert_eq!(eval("IF.EAGER(FALSE, 1, 2)"), Scalar::Integer(2));
assert_eq!(eval("IF.EAGER(1 = 1, \"yes\", \"no\")"), Scalar::String("yes".into()));
assert_eq!(eval("IF.EAGER(FALSE, 1)"), Scalar::Blank);
}
#[test]
fn if_eager_evaluates_both_branches() {
// The unselected branch is still evaluated, so its error propagates. (`1 / 0` is not an
// error in DAX — it is Infinity — so the fixture raises a real one.)
assert!(eval_result("IF.EAGER(TRUE, 1, ERROR(\"boom\"))").is_err());
assert!(eval_result("IF.EAGER(FALSE, ERROR(\"boom\"), 2)").is_err());
assert!(eval_result("IF.EAGER(FALSE, ERROR(\"boom\"))").is_err());
// The condition itself is also evaluated eagerly.
assert!(eval_result("IF.EAGER(ERROR(\"boom\"), 1, 2)").is_err());
// A non-boolean condition is rejected rather than silently treated as FALSE.
assert!(eval_result("IF.EAGER(\"maybe\", 1, 2)").is_err());
}

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