diff --git a/Cargo.lock b/Cargo.lock index be600e8701..abcd52ba97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1915,6 +1915,7 @@ dependencies = [ name = "gridcraft-cli" version = "0.12.1" dependencies = [ + "gridcraft-dax", "gridcraft-engine", "gridcraft-mcp", "log", @@ -1934,6 +1935,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "gridcraft-dax" +version = "0.12.1" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "gridcraft-engine" version = "0.12.1" diff --git a/Cargo.toml b/Cargo.toml index 6ba91fbf48..4a139d9c06 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ repository = "https://github.com/storytold/gridcraft" gridcraft-core = { path = "crates/core" } gridcraft-numfmt = { path = "crates/numfmt" } 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" } diff --git a/apps/gridcraft-cli/Cargo.toml b/apps/gridcraft-cli/Cargo.toml index 21e9580055..1137018b54 100644 --- a/apps/gridcraft-cli/Cargo.toml +++ b/apps/gridcraft-cli/Cargo.toml @@ -14,6 +14,7 @@ name = "gridcraft-cli" path = "src/main.rs" [dependencies] +gridcraft-dax = { workspace = true } gridcraft-engine = { workspace = true } gridcraft-mcp = { workspace = true } serde_json = { workspace = true } diff --git a/apps/gridcraft-cli/src/dax.rs b/apps/gridcraft-cli/src/dax.rs new file mode 100644 index 0000000000..93e78515e9 --- /dev/null +++ b/apps/gridcraft-cli/src/dax.rs @@ -0,0 +1,76 @@ +//! `gridcraft-cli dax`: format or dump the syntax tree of DAX text. + +use std::io::Read; + +use gridcraft_dax::{Expr, Query, TokenKind, parse_expression, parse_query, print_expression, print_query, tokenize}; + +use super::{Args, USAGE}; + +pub fn main(args: &[String]) -> Result<(), String> { + let action = args.first().map(String::as_str).ok_or_else(|| format!("missing dax action\n{USAGE}"))?; + let rest = args.get(1..).unwrap_or_default(); + match action { + "format" => format(rest), + "parse" => parse(rest), + other => Err(format!("unknown dax action `{other}`\n{USAGE}")), + } +} + +fn format(args: &[String]) -> Result<(), String> { + let text = read_input(args)?; + match parse_any(&text)? { + Parsed::Query(query) => outln!("{}", print_query(&query)), + Parsed::Expression(expr) => outln!("{}", print_expression(&expr)), + } + Ok(()) +} + +fn parse(args: &[String]) -> Result<(), String> { + let text = read_input(args)?; + match parse_any(&text)? { + Parsed::Query(query) => outln!("{query:#?}"), + Parsed::Expression(expr) => outln!("{expr:#?}"), + } + Ok(()) +} + +enum Parsed { + Query(Query), + Expression(Expr), +} + +/// Reads `TEXT`, `--file PATH`, or stdin (in that order of preference). Multiple positionals +/// are joined with spaces, so an unquoted `dax format 1 + 2` works. +fn read_input(args: &[String]) -> Result { + let parsed = Args::parse(args, &["file"], &[])?; + if let Some(path) = parsed.opt("file") { + if !parsed.positional.is_empty() { + return Err("give either TEXT or --file, not both".into()); + } + return std::fs::read_to_string(path).map_err(|e| format!("can't read {path}: {e}")); + } + if !parsed.positional.is_empty() { + return Ok(parsed.positional.join(" ")); + } + let mut text = String::new(); + std::io::stdin().read_to_string(&mut text).map_err(|e| format!("can't read stdin: {e}"))?; + Ok(text) +} + +/// Queries are tried first; a malformed `EVALUATE` reports its query error instead of a +/// misleading expression error. +fn parse_any(text: &str) -> Result { + match parse_query(text) { + Ok(query) => Ok(Parsed::Query(query)), + Err(query_error) => { + if starts_with_evaluate(text) { + return Err(query_error.to_string()); + } + parse_expression(text).map(Parsed::Expression).map_err(|e| e.to_string()) + } + } +} + +fn starts_with_evaluate(text: &str) -> bool { + tokenize(text).is_ok_and(|tokens| matches!(tokens.first().map(|token| &token.kind), Some(TokenKind::Evaluate))) +} diff --git a/apps/gridcraft-cli/src/main.rs b/apps/gridcraft-cli/src/main.rs index 5170ba0c5d..8e0d96b520 100644 --- a/apps/gridcraft-cli/src/main.rs +++ b/apps/gridcraft-cli/src/main.rs @@ -9,6 +9,7 @@ //! gridcraft-cli run [--in FILE | --sample NAME] [--cmd 'id={json}']... [--script FILE.jsonl] [--out FILE] [--print RANGE] [--quiet] //! gridcraft-cli commands [--json] [--search X] //! gridcraft-cli functions [--json] [--search X] [--category C] +//! gridcraft-cli dax format|parse [TEXT] [--file PATH] //! gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME] //! gridcraft-cli send [json] //! gridcraft-cli version | --version @@ -30,6 +31,7 @@ macro_rules! outln { } mod check; +mod dax; use gridcraft_engine::Session; use serde_json::{Value, json}; @@ -47,6 +49,8 @@ const USAGE: &str = "usage: blank lines and lines starting with # or // are skipped gridcraft-cli commands [--json] [--search X] gridcraft-cli functions [--json] [--search X] [--category C] + gridcraft-cli dax format [TEXT] [--file PATH] canonical DAX text (expression or EVALUATE query) + gridcraft-cli dax parse [TEXT] [--file PATH] DAX syntax tree gridcraft-cli mcp [--connect PORT] [--in FILE | --sample NAME] gridcraft-cli send [json] gridcraft-cli version"; @@ -81,6 +85,7 @@ fn main() -> ExitCode { Some("check") => return check::main(rest), Some("commands") => commands(rest), Some("functions") => functions(rest), + Some("dax") => dax::main(rest), Some("mcp") => mcp(rest), Some("send") => send(rest), Some(other) => Err(format!("unknown subcommand `{other}`\n{USAGE}")), diff --git a/apps/gridcraft-cli/tests/it/cli.rs b/apps/gridcraft-cli/tests/it/cli.rs index dde018ca8d..c46ec2ba8e 100644 --- a/apps/gridcraft-cli/tests/it/cli.rs +++ b/apps/gridcraft-cli/tests/it/cli.rs @@ -242,3 +242,37 @@ fn a_script_line_with_an_unknown_key_stops_the_run() { let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn dax_format_parse_and_errors() { + assert_eq!(ok(&["dax", "format", "1 + 2 * 3"]).trim(), "1 + 2 * 3"); + assert_eq!(ok(&["dax", "format", "(1 + 2) * 3"]).trim(), "(1 + 2) * 3"); + assert_eq!(ok(&["dax", "format", "-2 ^ 2"]).trim(), "-2 ^ 2"); + assert!(ok(&["dax", "parse", "1 + 2 * 3"]).contains("Binary")); + + assert_eq!(ok(&["dax", "format", "'Sales'[Amount] + 1"]).trim(), "'Sales'[Amount] + 1"); + assert!(ok(&["dax", "parse", "'It''s'[A]]B]"]).contains("It's")); + + let query = ok(&["dax", "format", "EVALUATE SUM('Sales'[Amount])"]); + assert_eq!(query.trim(), "EVALUATE SUM('Sales'[Amount])"); + assert!(ok(&["dax", "parse", "EVALUATE 1"]).contains("Query")); + + let o = run(&["dax", "parse", "1 +"]); + assert_eq!(o.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&o.stderr).contains("expected expression")); + let o = run(&["dax", "format", "EVALUATE 1 +"]); + assert_eq!(o.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&o.stderr).contains("end of input")); + + let dir = tmpdir("dax"); + let file = dir.join("expr.dax"); + std::fs::write(&file, "1 + 2 * 3").unwrap(); + assert_eq!(ok(&["dax", "format", "--file", file.to_str().unwrap()]).trim(), "1 + 2 * 3"); + let _ = std::fs::remove_dir_all(dir); + + let mut child = bin().args(["dax", "format"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + child.stdin.as_mut().unwrap().write_all(b"1 + 2 * 3").unwrap(); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8(out.stdout).unwrap().trim(), "1 + 2 * 3"); +} diff --git a/crates/dax/Cargo.toml b/crates/dax/Cargo.toml new file mode 100644 index 0000000000..4d2ac485f4 --- /dev/null +++ b/crates/dax/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "gridcraft-dax" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "GridCraft DAX language: lexer, Pratt parser, syntax tree and canonical printer" + +[lints] +workspace = true + +[dependencies] +thiserror = { workspace = true } diff --git a/crates/dax/README.md b/crates/dax/README.md new file mode 100644 index 0000000000..c8a5cdf19b --- /dev/null +++ b/crates/dax/README.md @@ -0,0 +1,270 @@ +# gridcraft-dax + +The DAX language for GridCraft: a tokenizer, a Pratt parser, a syntax tree, a canonical printer +the aggregation function catalog with static call validation, and the static type surface +(types, literals, inference and operator result tables). This crate is the foundation for the +statement PR. It has no evaluator and no engine dependency. + +```rust +use gridcraft_dax::{parse_expression, print_expression}; + +let expr = parse_expression("1 + 2 * 3")?; +assert_eq!(print_expression(&expr), "1 + 2 * 3"); + +let query = gridcraft_dax::parse_query("EVALUATE SUM('Sales'[Amount])")?; +assert_eq!(gridcraft_dax::print_query(&query), "EVALUATE SUM('Sales'[Amount])"); +# Ok::<(), gridcraft_dax::ParseError>(()) +``` + +## Public API + +| Item | Meaning | +| --- | --- | +| `parse_expression(&str) -> Result` | Parse one expression. One leading `=` (as typed in some editors) is accepted and ignored. | +| `print_expression(&Expr) -> String` | Canonical text. | +| `parse_query(&str) -> Result` | Parse `EVALUATE ` (only statement form in this PR). | +| `print_query(&Query) -> String` | Canonical query text. | +| `tokenize(&str) -> Result, 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, Query}` | Syntax tree. | +| `functions::{catalog, lookup}` | The 22 aggregation functions, looked up case-insensitively. | +| `functions::{FunctionSpec, FunctionCategory, ParamKind, ReturnType, BlankPolicy, FunctionFlags, Parameter, Overload}` | Catalog record types. | +| `validate_call(&Call) -> Vec` | Arity/kind checks for one call; empty for valid or unknown functions. | +| `validate_expression(&Expr) -> Vec` | 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. | +| `MAX_INPUT_LEN` (8192 bytes) / `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 + | Call(Call) name: Name, args: Vec + | Unary { op, expr } op: UnaryOp (Plus | Neg | Not) + | Binary { op, left, right } op: BinaryOp + | Table(Vec) { value, ... } + | Tuple(Vec) (value, ...) +``` + +`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)* ] "}" +name := IDENT | "[" column "]" | "'" table "'" +qualified := (IDENT | "'" table "'") "[" column "]" +query := EVALUATE expression +``` + +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. + +### Case and escapes + +- Keywords (`NOT`, `IN`, `EVALUATE`, `TRUE`, `FALSE`) are case-insensitive. `TRUE`/`FALSE` are + literals unless followed by `(` (then they are calls to a function of that name). +- 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 DAX Guide operator table (tighter first); equal precedence evaluates left to +right, except `^`: + +| Level | Operators | Associativity | +| --- | --- | --- | +| 1 | grouping `()`, function calls, `IN` | — (`IN` is an infix operator) | +| 2 | `^` | right | +| 3 | unary `+`, `-` | prefix | +| 4 | `*`, `/` | left | +| 5 | binary `+`, `-` | left | +| 6 | `&` | left | +| 7 | `=`, `==`, `<>`, `<`, `>`, `<=`, `>=` | 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` takes a list (`expr IN { v1, v2 }`) or a table expression +(`expr IN VALUES(T[Col])`). + +Excel evaluates `2^3^2` as `512` (`2^(3^2)`), so `^` is right-associative even though the generic +DAX Guide note says operators of equal precedence go left to right. 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` infers literals, unary `+`/`-`/`NOT`, binary operators, +`TRUE()`/`FALSE()`/`BLANK()` calls, and table constructors. Name references and other function +calls return `InferredType::Unknown` because they need the model or a function catalog. `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 + +Input is capped at 8192 bytes and expression nesting at 256 levels; both produce an error, never a +stack overflow. The printer and `Expr::walk` use explicit stacks, and the parser's binary loop is +iterative for left-associated chains. + +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. + +## Aggregation function catalog + +`functions::catalog()` returns the 22 functions of +[dax.guide/functions/aggregation](https://dax.guide/functions/aggregation/), in that order. +`functions::lookup(name)` is case-insensitive. Each record carries its descriptive signature +(`params`, with `optional` markers), exact `overloads`, `return_type`, `flags` +(`iterator`, `not_recommended`, `excel_compatible`, `direct_query_limited`), `sugar_of`, +`blank_policy`, `description` and `examples`. Every example in the catalog parses with +`parse_expression` and validates. + +| 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 and any text is 0; 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 only +when it is certainly scalar — a literal or an operator expression — so `COUNTROWS ( 1 )` fails +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). `Expression`, `Scalar`, `Logical` and `Any` are not statically decidable and are +recorded for documentation and future type checking, so the third `Variant` argument of +`MAXX`/`MINX` accepts any expression. + +## Extending in later PRs + +- `Query` currently holds only `evaluate`. `DEFINE`/`VAR` clauses (including query-level + `VAR`) extend `Query` and `parse_query`; `Expr` and the operator grammar stay unchanged. +- The lexer already emits `=>` (`TokenKind::Arrow`) for user-defined functions. +- `Call`, `NameRef` and `NameStyle` keep spelling/quoting so catalog and type work can resolve + names without re-lexing. +- `types::infer_type` deliberately knows only `TRUE()`, `FALSE()` and `BLANK()`. The function + PR supplies signatures for everything else; `InferredType::Unknown` marks those calls today. + +## Example + +```sh +cargo run -p gridcraft-dax --example parse -- "1 + 2 * 3" +cargo run -p gridcraft-dax --example parse -- "EVALUATE SUM('Sales'[Amount])" +echo 'NOT TRUE || FALSE && TRUE' | cargo run -p gridcraft-dax --example parse +``` diff --git a/crates/dax/examples/parse.rs b/crates/dax/examples/parse.rs new file mode 100644 index 0000000000..08498bb6ce --- /dev/null +++ b/crates/dax/examples/parse.rs @@ -0,0 +1,43 @@ +//! 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> { + let mut text = std::env::args().skip(1).collect::>().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()); + } + + match parse_query(text) { + Ok(query) => { + println!("Query"); + println!("{query:#?}"); + println!("Canonical: {}", print_query(&query)); + } + Err(query_error) => { + if starts_with_evaluate(text) { + return Err(query_error.into()); + } + let expr = parse_expression(text)?; + println!("AST"); + println!("{expr:#?}"); + println!("Canonical: {}", print_expression(&expr)); + } + } + Ok(()) +} + +fn starts_with_evaluate(text: &str) -> bool { + tokenize(text).is_ok_and(|tokens| matches!(tokens.first().map(|token| &token.kind), Some(TokenKind::Evaluate))) +} diff --git a/crates/dax/src/ast.rs b/crates/dax/src/ast.rs new file mode 100644 index 0000000000..96b98960de --- /dev/null +++ b/crates/dax/src/ast.rs @@ -0,0 +1,344 @@ +//! DAX syntax tree. +//! +//! Every node carries a [`Span`] in byte offsets into the source text. [`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) -> Self { + Name { text: text.into(), style: NameStyle::Bare } + } + + pub fn quoted(text: impl Into) -> Self { + Name { text: text.into(), style: NameStyle::Quoted } + } + + pub fn bracketed(text: impl Into) -> 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, + 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, +} + +/// 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 . +#[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 DAX Guide: parentheses/calls/`IN`, `^`, unary sign, `* /`, `+ -`, `&`, + /// comparisons, `NOT`, `&&`, `||`. + pub const fn precedence(self) -> u8 { + match self { + BinaryOp::In => 100, + BinaryOp::Pow => 90, + BinaryOp::Mul | BinaryOp::Div => 70, + BinaryOp::Add | BinaryOp::Sub => 60, + BinaryOp::Concat => 50, + BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => 40, + BinaryOp::And => 20, + BinaryOp::Or => 10, + } + } + + /// DAX binary operators associate to the left, except `^`, which is right-associative + /// (verified against Excel: `2^3^2` is 512). + pub const fn is_left_associative(self) -> bool { + !matches!(self, BinaryOp::Pow) + } + + pub const fn is_right_associative(self) -> bool { + matches!(self, BinaryOp::Pow) + } + + 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, + }, + Binary { + op: BinaryOp, + left: Box, + right: Box, + }, + /// A table constructor `{ 1, 2 }`. Rows are [`ExprKind::Tuple`] values. + Table(Vec), + /// A row constructor / parenthesised comma list `(1, "a")`. + Tuple(Vec), +} + +/// 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::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::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 + } +} + +/// `EVALUATE `. The statements PR extends this type. +#[derive(Clone, Debug, PartialEq)] +pub struct Query { + pub evaluate: Expr, +} diff --git a/crates/dax/src/functions.rs b/crates/dax/src/functions.rs new file mode 100644 index 0000000000..c8e9bf0d18 --- /dev/null +++ b/crates/dax/src/functions.rs @@ -0,0 +1,543 @@ +//! Semantic catalog of the DAX aggregation functions. +//! +//! The catalog records the documented signature of every function in +//! — arity, parameter kinds, overloads, return type, +//! iterator 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. This PR ships the aggregation family only. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FunctionCategory { + Aggregation, +} + +/// 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, +} + +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", + } + } +} + +/// 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, +} + +/// 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, + /// 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, not_recommended: bool, excel_compatible: bool, direct_query_limited: bool) -> Self { + FunctionFlags { iterator, 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], +} + +impl Overload { + pub const fn arity(self) -> usize { + self.params.len() + } +} + +const fn overload(params: &'static [ParamKind]) -> Overload { + Overload { params } +} + +/// 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.arity() == arity) + } +} + +const fn standard(iterator: bool) -> FunctionFlags { + FunctionFlags::new(iterator, false, true, true) +} + +/// All aggregation functions, in the order listed by dax.guide. +pub static CATALOG: [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, 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, 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, true), + sugar_of: Some("DISTINCTCOUNT"), + blank_policy: BlankPolicy::Unspecified, + description: "Counts distinct values in a column, excluding BLANK. Syntax sugar for \ + DISTINCTCOUNT with an ISBLANK filter. 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: Some("MAXX"), + blank_policy: BlankPolicy::Unspecified, + description: "With one argument, the largest non-blank value of a column (internally \ + MAXX); 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: Some("MINX"), + blank_policy: BlankPolicy::Unspecified, + description: "With one argument, the smallest non-blank value of a column (internally \ + MINX); 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] )", + ], + }, +]; + +/// Every aggregation function, in dax.guide order. +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)) +} diff --git a/crates/dax/src/lexer.rs b/crates/dax/src/lexer.rs new file mode 100644 index 0000000000..34fbbd7da7 --- /dev/null +++ b/crates/dax/src/lexer.rs @@ -0,0 +1,524 @@ +//! 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. + +use crate::ast::{DateTimeLiteral, Span}; + +/// Longest input accepted, 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; + +/// 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, + /// `=>`, reserved for user-defined functions (a later PR). + Arrow, + 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, 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. +pub fn tokenize(src: &str) -> Result, LexError> { + if src.len() > MAX_INPUT_LEN { + return Err(LexError::new(format!("input is too long ({} bytes, limit {MAX_INPUT_LEN})", src.len()), Span::new(0, src.len()))); + } + + 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 = 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::().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::().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; + } + 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 { + 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()); + } + if day == 0 || day > days_in_month(year, month) { + 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 { + 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::().map_err(|_| format!("invalid date/time literal: the {unit} is out of range")) +} + +const fn is_leap_year(year: u32) -> bool { + year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) +} + +const fn days_in_month(year: u32, month: u32) -> u32 { + match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if is_leap_year(year) => 29, + 2 => 28, + _ => 0, + } +} diff --git a/crates/dax/src/lib.rs b/crates/dax/src/lib.rs new file mode 100644 index 0000000000..2757c5dc9c --- /dev/null +++ b/crates/dax/src/lib.rs @@ -0,0 +1,36 @@ +//! The DAX language: tokenizer, syntax tree, Pratt parser, canonical printer and static types. +//! +//! This crate covers the DAX expression grammar, the aggregation function catalog with static +//! call validation, the static type surface (literal classification, inference and the documented +//! operator result tables) and, for now, the query form `EVALUATE `. It does not +//! evaluate expressions. Later PRs extend [`Query`] with `DEFINE`/`VAR` clauses. +//! +//! ``` +//! 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 functions; +pub mod lexer; +pub mod parser; +pub mod printer; +pub mod types; +pub mod validate; + +pub use ast::{BinaryOp, Call, DateTimeLiteral, Expr, ExprKind, Literal, Name, NameRef, NameStyle, Query, Span, UnaryOp}; +pub use functions::{ + BlankPolicy, CATALOG, FunctionCategory, FunctionFlags, FunctionSpec, Overload, ParamKind, Parameter, ReturnType, catalog, lookup, +}; +pub use lexer::{LexError, MAX_INPUT_LEN, Token, TokenKind, tokenize}; +pub use parser::{MAX_DEPTH, ParseError, parse_expression, parse_query}; +pub use printer::{print_expression, print_query}; +pub use validate::{ValidationError, ValidationErrorKind, validate_call, validate_expression}; + +#[cfg(test)] +mod tests; diff --git a/crates/dax/src/parser.rs b/crates/dax/src/parser.rs new file mode 100644 index 0000000000..02cae523e4 --- /dev/null +++ b/crates/dax/src/parser.rs @@ -0,0 +1,354 @@ +//! Pratt parser: tokens → [`Expr`] / [`Query`]. +//! +//! Binding powers encode the DAX operator table from (tighter +//! binds first): parentheses, function calls and `IN`; `^`; unary `+`/`-`; `*`/`/`; binary +//! `+`/`-`; `&`; comparisons; `NOT`; `&&`; `||`. All operators are left-associative except +//! `^`, which Excel evaluates right-associatively (`2^3^2` is 512). + +use crate::ast::{BinaryOp, Call, Expr, ExprKind, Literal, Name, NameRef, Query, Span, UnaryOp}; +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, span: Span) -> Self { + ParseError { message: message.into(), span } + } +} + +impl From 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 { + 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. This PR accepts only `EVALUATE `; the statements PR will +/// extend [`Query`] with `DEFINE`/`VAR` clauses. +pub fn parse_query(src: &str) -> Result { + let tokens = tokenize(src)?; + let mut parser = Parser { tokens, i: 0, depth: 0 }; + if !matches!(parser.peek(), TokenKind::Evaluate) { + return Err(parser.error_here("expected `EVALUATE`")); + } + parser.next(); + let evaluate = parser.expr(0)?; + parser.expect_eof()?; + ensure_depth(&evaluate)?; + Ok(Query { evaluate }) +} + +/// 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(()) +} + +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::LParen => "`(`".into(), + TokenKind::RParen => "`)`".into(), + TokenKind::LBrace => "`{`".into(), + TokenKind::RBrace => "`}`".into(), + TokenKind::Comma => "`,`".into(), + TokenKind::Eof => "end of input".into(), + } +} + +struct Parser { + tokens: Vec, + 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) -> ParseError { + ParseError::new(message, self.peek_span()) + } + + fn expect(&mut self, kind: TokenKind, context: &str) -> Result { + 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 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 { + 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 { + self.enter()?; + let mut lhs = self.prefix()?; + while let Some(op) = self.binary_op() { + let bp = op.precedence(); + if bp < min_bp { + break; + } + self.next(); + // `^` is right-associative; every other binary operator is left-associative. + 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. + if lhs.depth().max(rhs.depth()) >= MAX_DEPTH { + return Err(self.error_here(format!("expression is nested too deeply (limit {MAX_DEPTH})"))); + } + 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 { + 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) => 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 { + 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)) + } + + /// Consumes a bracketed column that follows a table name. + fn qualified_name(&mut self, table: Name, table_span: Span) -> Result { + 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 { + 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 { + 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 { + 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))) + } +} diff --git a/crates/dax/src/printer.rs b/crates/dax/src/printer.rs new file mode 100644 index 0000000000..408bb19c23 --- /dev/null +++ b/crates/dax/src/printer.rs @@ -0,0 +1,180 @@ +//! 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::{Call, Expr, ExprKind, Literal, Name, NameRef, NameStyle, Query, UnaryOp}; + +/// 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: `EVALUATE `. +pub fn print_query(query: &Query) -> String { + let mut out = String::from("EVALUATE "); + write_expr(&mut out, &query.evaluate, 0); + out +} + +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), +} + +fn write_expr(out: &mut String, root: &Expr, root_min_bp: u8) { + let mut stack: Vec> = vec![Task::Expr(root, root_min_bp)]; + + while let Some(task) = stack.pop() { + match task { + Task::Text(text) => out.push_str(text), + 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(", ")); + } + } + } + } + }, + } + } +} diff --git a/crates/dax/src/tests.rs b/crates/dax/src/tests.rs new file mode 100644 index 0000000000..84fe149495 --- /dev/null +++ b/crates/dax/src/tests.rs @@ -0,0 +1,459 @@ +use crate::ast::*; +use crate::lexer::TokenKind; +use crate::{MAX_DEPTH, MAX_INPUT_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_except_exponentiation() { + 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)); + + let expr = expression("2 ^ 3 ^ 2"); + let (op, left, right) = binary(&expr); + assert_eq!(*op, BinaryOp::Pow); + assert!(matches!(&left.kind, ExprKind::Literal(Literal::Integer(n)) if *n == 2)); + assert!(matches!(&right.kind, ExprKind::Binary { op: BinaryOp::Pow, .. })); + + 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` binds tighter than `^`, comparisons and arithmetic in DAX's table. + let expr = expression("2 ^ 3 IN { 8 }"); + let (op, left, right) = binary(&expr); + assert_eq!(*op, BinaryOp::Pow); + assert!(matches!(&left.kind, ExprKind::Literal(Literal::Integer(n)) if *n == 2)); + assert!(matches!(&right.kind, ExprKind::Binary { op: BinaryOp::In, .. })); + + let expr = expression("1 + 2 IN { 3 }"); + let (op, left, right) = binary(&expr); + assert_eq!(*op, BinaryOp::Add); + assert!(matches!(&left.kind, ExprKind::Literal(Literal::Integer(n)) if *n == 1)); + assert!(matches!(&right.kind, ExprKind::Binary { op: BinaryOp::In, .. })); + + 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, .. })); +} + +#[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_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); + + 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::>().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)); +} diff --git a/crates/dax/src/types.rs b/crates/dax/src/types.rs new file mode 100644 index 0000000000..77dda12557 --- /dev/null +++ b/crates/dax/src/types.rs @@ -0,0 +1,697 @@ +//! DAX data types, literal classification, static inference and operator result tables. +//! +//! The eight scalar types are [`DataType`]'s variants, matching +//! : 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 { + match self { + InferredType::Data(data_type) => Some(data_type), + InferredType::Blank | InferredType::Table | InferredType::Unknown => None, + } + } +} + +impl From for InferredType { + fn from(value: DataType) -> Self { + InferredType::Data(value) + } +} + +impl From 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, + } +} + +/// Infers the static type of an expression. +/// +/// Name references are [`InferredType::Unknown`] (they need the model), as are calls other than +/// `TRUE()`, `FALSE()` and `BLANK()`. Incompatible known operands produce a [`TypeError`]. +pub fn infer_type(expr: &Expr) -> Result { + 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 = infer_type(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 + } + _ => infer_type(left)?, + }; + let right = infer_type(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) + } + } +} + +/// `TRUE()`, `FALSE()` and `BLANK()` are inferable without a function catalog. Everything else +/// returns [`InferredType::Unknown`]; function signatures are owned by the functions PR. +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; + } + } + 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 { + 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 { + 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 { + 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 { + 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 { + 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) + } + } + BinaryOp::Pow => Ok(InferredType::Blank), + _ => 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 { + 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 { + 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; 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 { + 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 { + let row = numeric_index(left)?; + let column = numeric_index(right)?; + matrix.get(row)?.get(column).copied() +} + +fn multiplication_cell(left: DataType, right: DataType) -> Option { + 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 +} diff --git a/crates/dax/src/validate.rs b/crates/dax/src/validate.rs new file mode 100644 index 0000000000..eb98038ddc --- /dev/null +++ b/crates/dax/src/validate.rs @@ -0,0 +1,173 @@ +//! Static validation of aggregation-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: +//! +//! - 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 an obvious scalar literal or scalar operator expression +//! (`COUNTROWS ( 1 )`). 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 aggregation 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 { + 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 { + 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 { + 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.arity() == 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.params.get(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.params.get(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 => 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", + } +} diff --git a/crates/dax/tests/aggregation.rs b/crates/dax/tests/aggregation.rs new file mode 100644 index 0000000000..a790793b71 --- /dev/null +++ b/crates/dax/tests/aggregation.rs @@ -0,0 +1,528 @@ +//! 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}; + +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 { + validate_expression(&parse(src)) +} + +fn call_errors(src: &str) -> Vec { + 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 { + 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> { + spec.overload_for(arity).map(|overload| overload.params.to_vec()) +} + +#[test] +fn catalog_has_every_aggregation_function_exactly_once_with_documented_arity() { + let specs = catalog(); + assert_eq!(specs.len(), FUNCTIONS.len()); + + for (name, min_args, max_args) in FUNCTIONS { + let matches: Vec<&FunctionSpec> = specs.iter().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 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 = 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 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"), + ("MAX", "MAXX"), + ("MIN", "MINX"), + ("PRODUCT", "PRODUCTX"), + ("SUM", "SUMX"), + ("DISTINCTCOUNTNOBLANK", "DISTINCTCOUNT"), + ] { + assert_eq!(spec(name).sugar_of, Some(target), "{name} sugar"); + } + + for name in [ + "APPROXIMATEDISTINCTCOUNT", + "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 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> = 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 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 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"); +} diff --git a/crates/dax/tests/data_types.rs b/crates/dax/tests/data_types.rs new file mode 100644 index 0000000000..6f582d62a3 --- /dev/null +++ b/crates/dax/tests/data_types.rs @@ -0,0 +1,549 @@ +//! 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 { + infer_type(&parse(src)) +} + +fn data(data_type: DataType) -> InferredType { + InferredType::Data(data_type) +} + +fn arithmetic(op: BinaryOp, left: DataType, right: DataType) -> Result { + 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; its type is outside this crate's catalog. + assert!(matches!(parse("TRUE(1)").kind, ExprKind::Call(_))); + assert_eq!(infer("TRUE(1)"), Ok(InferredType::Unknown)); + assert_eq!(infer("FALSE(1)"), Ok(InferredType::Unknown)); +} + +#[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)), + ] { + assert_eq!(infer(src), Ok(expected), "{src}"); + } + + for src in ["[Amount]", "SUM(1, 2)", "VALUES(T[Col])", "\"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!(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))); +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index cd3229e8be..e8fe28bb9c 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -30,6 +30,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("numfmt", Class::Layer(0)), ("pdf", Class::Layer(0)), ("formula", Class::Layer(1)), + ("dax", Class::Layer(1)), ("functions", Class::Layer(1)), ("model", Class::Layer(2)), ("calc", Class::Layer(2)),