From a89acaa9a6e119673277d5f2f59433449a8d51ed Mon Sep 17 00:00:00 2001 From: alosslessdev Date: Thu, 5 Nov 2026 00:36:35 -0500 Subject: [PATCH] dax: static types, binder and call validation (#2228) --- crates/dax/src/binder.rs | 396 +++++++++++++++++ crates/dax/src/model.rs | 371 ++++++++++++++++ crates/dax/src/types.rs | 732 ++++++++++++++++++++++++++++++++ crates/dax/src/validate.rs | 185 ++++++++ crates/dax/tests/aggregation.rs | 532 +++++++++++++++++++++++ crates/dax/tests/binder.rs | 205 +++++++++ crates/dax/tests/data_types.rs | 569 +++++++++++++++++++++++++ 7 files changed, 2990 insertions(+) create mode 100644 crates/dax/src/binder.rs create mode 100644 crates/dax/src/model.rs create mode 100644 crates/dax/src/types.rs create mode 100644 crates/dax/src/validate.rs create mode 100644 crates/dax/tests/aggregation.rs create mode 100644 crates/dax/tests/binder.rs create mode 100644 crates/dax/tests/data_types.rs diff --git a/crates/dax/src/binder.rs b/crates/dax/src/binder.rs new file mode 100644 index 000000000..c138dca59 --- /dev/null +++ b/crates/dax/src/binder.rs @@ -0,0 +1,396 @@ +//! Name binding for DAX expressions and measures. +//! +//! The binder resolves table names, `Table[Column]` references, measures and expression-level +//! `VAR` names against a [`DataModel`]. It validates catalogued function calls with the same +//! arity/kind rules as [`crate::validate`], and builds the measure dependency graph. +//! +//! It is deliberately static: row context and filter context are evaluator concerns. A bracketed +//! column that is not qualified by a table is left as [`BoundExpr::UnqualifiedColumn`] so the +//! evaluator can resolve it from the current row context. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::ast::{BinaryOp, Literal, NameRef, UnaryOp}; +use crate::model::DataModel; +use crate::{Call, Expr, ExprKind, FunctionSpec, ParamKind, lookup, parse_expression, validate_call}; + +/// A name-resolution error with the source span. +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[error("{message} at bytes {}..{}", span.start, span.end)] +pub struct BindError { + pub message: String, + pub span: crate::Span, +} + +impl BindError { + fn new(message: impl Into, span: crate::Span) -> Self { + BindError { message: message.into(), span } + } +} + +/// The bound form of an expression. +#[derive(Clone, Debug, PartialEq)] +pub enum BoundExpr { + Literal(Literal), + /// A resolved `Table[Column]` reference. + Column { + table: usize, + column: usize, + }, + /// `[Column]` without a table qualifier: resolved from the evaluator's row context. + UnqualifiedColumn { + name: String, + }, + /// A model measure reference. + Measure(usize), + /// A table reference. + Table(usize), + /// A catalogued function call with bound arguments. + Call { + spec: &'static FunctionSpec, + args: Vec, + }, + Unary { + op: UnaryOp, + expr: Box, + }, + Binary { + op: BinaryOp, + left: Box, + right: Box, + }, + /// `{ value, ... }`. + TableConstructor(Vec), + /// `( value, ... )`. + Tuple(Vec), + /// A variable reference, indexed in the enclosing [`BoundExpr::VarReturn`]. + Variable { + index: usize, + name: String, + }, + /// A function-specific keyword argument (`DAY` in `DATEDIFF`, a type name in `DATATABLE`). + Keyword(String), + /// `VAR name = expr ... RETURN body`. + VarReturn { + vars: Vec, + body: Box, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct BoundVariable { + pub name: String, + pub expr: BoundExpr, +} + +/// A bound measure with its direct measure dependencies. +#[derive(Clone, Debug, PartialEq)] +pub struct BoundMeasure { + pub name: String, + pub expr: BoundExpr, + pub dependencies: BTreeSet, +} + +/// Binds expressions against one model. +pub struct Binder<'a> { + model: &'a DataModel, +} + +impl<'a> Binder<'a> { + pub fn new(model: &'a DataModel) -> Self { + Binder { model } + } + + pub fn model(&self) -> &'a DataModel { + self.model + } + + /// Binds an expression with no variables in scope. + pub fn bind_expression(&self, expr: &Expr) -> Result { + self.bind_with_vars(expr, &mut Vec::new()) + } + + /// Parses and binds a measure formula. The model's measures must have been prepared with + /// [`DataModel::parse_formulas`]. + pub fn bind_measure(&self, name: &str) -> Result { + let index = self.model.measure_index(name).ok_or_else(|| BindError::new(format!("unknown measure `{name}`"), crate::Span::empty()))?; + let measure = &self.model.measures[index]; + if measure.expr.is_none() { + return Err(BindError::new( + format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name), + crate::Span::empty(), + )); + } + let Some(formula) = measure.expr.as_ref() else { + return Err(BindError::new( + format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name), + crate::Span::empty(), + )); + }; + let expr = self.bind_expression(formula)?; + let mut dependencies = BTreeSet::new(); + collect_measure_names(self.model, &expr, &mut dependencies); + Ok(BoundMeasure { name: measure.name.clone(), expr, dependencies }) + } + + /// Builds the direct measure dependency graph and rejects cycles. + pub fn dependency_graph(&self) -> Result>, BindError> { + let mut graph = BTreeMap::new(); + for measure in &self.model.measures { + let bound = self.bind_measure(&measure.name)?; + graph.insert(bound.name, bound.dependencies); + } + let mut state: BTreeMap = BTreeMap::new(); + for name in graph.keys() { + self.visit(name, &graph, &mut state)?; + } + Ok(graph) + } + + fn visit(&self, name: &str, graph: &BTreeMap>, state: &mut BTreeMap) -> Result<(), BindError> { + // Iterative: a measure chain comes from the model JSON, so its length must not grow the + // call stack (a long chain would otherwise abort the process instead of returning an error). + if state.get(name).copied() == Some(2) { + return Ok(()); + } + let empty = BTreeSet::new(); + state.insert(name.to_string(), 1); + let mut stack: Vec<(&str, std::collections::btree_set::Iter<'_, String>)> = vec![(name, graph.get(name).unwrap_or(&empty).iter())]; + while let Some((current, dependencies)) = stack.last_mut() { + match dependencies.next() { + Some(dependency) => match state.get(dependency.as_str()).copied() { + Some(2) => {} + Some(1) => { + return Err(BindError::new(format!("circular measure dependency involving `{dependency}`"), crate::Span::empty())); + } + _ => { + state.insert(dependency.clone(), 1); + stack.push((dependency.as_str(), graph.get(dependency).unwrap_or(&empty).iter())); + } + }, + None => { + state.insert((*current).to_string(), 2); + stack.pop(); + } + } + } + Ok(()) + } + + fn bind_with_vars(&self, expr: &Expr, vars: &mut Vec) -> Result { + match &expr.kind { + ExprKind::Literal(literal) => Ok(BoundExpr::Literal(literal.clone())), + ExprKind::Name(name) => self.bind_name(name, expr.span, vars), + ExprKind::Call(call) => self.bind_call(call, expr.span, vars), + ExprKind::Unary { op, expr: inner } => Ok(BoundExpr::Unary { op: *op, expr: Box::new(self.bind_with_vars(inner, vars)?) }), + ExprKind::Binary { op, left, right } => Ok(BoundExpr::Binary { + op: *op, + left: Box::new(self.bind_with_vars(left, vars)?), + right: Box::new(self.bind_with_vars(right, vars)?), + }), + ExprKind::Table(items) => { + Ok(BoundExpr::TableConstructor(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::>()?)) + } + ExprKind::Tuple(items) => Ok(BoundExpr::Tuple(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::>()?)), + ExprKind::VarReturn { vars: declarations, body } => { + let mut bound = Vec::with_capacity(declarations.len()); + let mut names = vars.clone(); + for declaration in declarations { + let value = self.bind_with_vars(&declaration.expr, &mut names)?; + names.push(declaration.name.text.clone()); + bound.push(BoundVariable { name: declaration.name.text.clone(), expr: value }); + } + let body = self.bind_with_vars(body, &mut names)?; + Ok(BoundExpr::VarReturn { vars: bound, body: Box::new(body) }) + } + } + } + + fn bind_name(&self, name: &NameRef, span: crate::Span, vars: &[String]) -> Result { + if let Some(table) = &name.table { + let table_index = self.model.table_index(&table.text).ok_or_else(|| BindError::new(format!("unknown table `{}`", table.text), span))?; + if let Some(column_index) = self.model.column_index(table_index, &name.name.text) { + return Ok(BoundExpr::Column { table: table_index, column: column_index }); + } + // `Sales[Total Sales]` names a measure homed on the qualifying table; DAX allows the + // table qualifier on a measure reference and only rejects it for another table. + if let Some(index) = self.model.measure_index(&name.name.text) + && let Some(home) = self.model.measures[index].table.as_deref() + { + if self.model.table_index(home) == Some(table_index) { + return Ok(BoundExpr::Measure(index)); + } + return Err(BindError::new(format!("measure `{}` belongs to table `{}`, not `{}`", name.name.text, home, table.text), span)); + } + return Err(BindError::new(format!("unknown column `{}` in table `{}`", name.name.text, table.text), span)); + } + + // A bracketed name is always a model object reference (`[Measure]`, `[Column]`), never a + // variable: DAX requires bare identifiers for variables, so `VAR Total = 1 ... [Total]` + // refers to the measure, not the variable. + if name.name.style == crate::NameStyle::Bracketed { + if let Some(index) = self.model.measure_index(&name.name.text) { + return Ok(BoundExpr::Measure(index)); + } + // A bracketed name may be a row-context column; the evaluator resolves it. + return Ok(BoundExpr::UnqualifiedColumn { name: name.name.text.clone() }); + } + + if let Some(index) = vars.iter().rposition(|var| var.eq_ignore_ascii_case(&name.name.text)) { + return Ok(BoundExpr::Variable { index, name: name.name.text.clone() }); + } + + if let Some(index) = self.model.table_index(&name.name.text) { + return Ok(BoundExpr::Table(index)); + } + if let Some(index) = self.model.measure_index(&name.name.text) { + return Ok(BoundExpr::Measure(index)); + } + Err(BindError::new(format!("unknown name `{}`", name.name.text), span)) + } + + fn bind_call(&self, call: &Call, span: crate::Span, vars: &mut Vec) -> Result { + let Some(spec) = lookup(&call.name.text) else { + return Err(BindError::new(format!("unknown DAX function `{}`", call.name.text), span)); + }; + if let Some(error) = validate_call(call).into_iter().next() { + return Err(BindError::new(error.message, span)); + } + let mut args = Vec::with_capacity(call.args.len()); + for (index, arg) in call.args.iter().enumerate() { + // Documented enum parameters (intervals, ties, blanks, text type names) are written + // as bare names. The parser cannot tell them from table/measure names, but the + // catalog's parameter kind can: a Text position only accepts a literal or a keyword. + let expected = spec.overload_for(call.args.len()).and_then(|overload| overload.params.get(index)).copied(); + let keyword = match spec.name { + "DATATABLE" if index % 2 == 1 => keyword_name(arg), + "CONVERT" if index == 1 => keyword_name(arg), + // RANKX's Ties argument is documented as `Dense` but catalogued as a Scalar. + "RANKX" if index == 4 => keyword_name(arg), + "DATEDIFF" if index == 2 => keyword_name(arg), + // TOPN's `(expression, Order)` pairs: ASC/DESC sit at every odd index from 3. + "TOPN" if index >= 3 && index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]), + "CROSSFILTER" if index == 2 => clause_keyword(arg, &["ONE", "ONEWAY", "BOTH", "TWOWAY", "NONE"]), + // Window/relation clauses take bare enum words: `ORDERBY(x, DESC)`, + // `WINDOW(1, ABS, 1, ABS, ...)`, `INDEX(..., KEEP, PARTITIONBY(...))`, and the + // LOOKUP associated-columns behaviour (`INFERRED`). + "ORDERBY" if index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]), + "INDEX" | "OFFSET" if index >= 2 => clause_keyword(arg, WINDOW_KEYWORDS), + // FromType/ToType are optional, so the blanks/reset slots move with the layout; + // `window_table` identifies each slot by its value. + "WINDOW" if index >= 1 => clause_keyword(arg, WINDOW_KEYWORDS), + "LOOKUP" | "LOOKUPWITHTOTALS" if index % 2 == 1 && index + 1 == call.args.len() => { + clause_keyword(arg, &["EXPLICIT", "INFERRED", "DEFAULT"]) + } + // PATHITEM's optional Type is documented as `TEXT`/`INTEGER` but catalogued as + // `Any` so that the numeric `0`/`1` spellings still bind. + "PATHITEM" | "PATHITEMREVERSE" if index == 2 => clause_keyword(arg, &["TEXT", "INTEGER"]), + _ if matches!(expected, Some(ParamKind::Text)) => keyword_name(arg), + _ => visual_keyword_name(spec.name, index, arg), + } + // A real table, measure or variable name always wins: `RANK(Sales, ORDERBY(...))` + // uses the table in a position whose documented overload would otherwise be `Ties`. + .filter(|keyword| !self.bare_name_resolves(keyword, vars)); + if let Some(keyword) = keyword { + args.push(BoundExpr::Keyword(keyword)); + } else { + args.push(self.bind_with_vars(arg, vars)?); + } + } + Ok(BoundExpr::Call { spec, args }) + } +} + +fn keyword_name(expr: &Expr) -> Option { + match &expr.kind { + ExprKind::Name(name) if name.table.is_none() && name.name.style == crate::NameStyle::Bare => Some(name.name.text.clone()), + _ => None, + } +} + +impl Binder<'_> { + /// Whether a bare name denotes a model table, measure or expression-level variable. + fn bare_name_resolves(&self, name: &str, vars: &[String]) -> bool { + self.model.table_index(name).is_some() + || self.model.measure_index(name).is_some() + || vars.iter().any(|variable| variable.eq_ignore_ascii_case(name)) + } +} + +/// Bare identifiers that visual-calculation functions accept where their syntax documents an +/// axis, an ORDERBY flag, a blank-ordering enumeration or a reset clause. These words are not +/// names in the model, so they must become [`BoundExpr::Keyword`] instead of failing resolution. +fn visual_keyword_name(function: &str, index: usize, arg: &Expr) -> Option { + let word = keyword_name(arg)?; + is_visual_keyword(function, index, &word).then_some(word) +} + +/// Whether `word` is a documented keyword at the 0-based `index` of a visual-calculation call. +/// +/// The positions mirror the Microsoft syntax for each function, e.g. `FIRST ( [, ] +/// [, ][, ][, reset] )` and `RANGE ( [, ][, ] +/// [, ][, ][, ] )`. `COLLAPSE`/`EXPAND` also have navigation-only forms +/// whose first argument is the axis (`COLLAPSE ( [, N] )`). +fn is_visual_keyword(function: &str, index: usize, word: &str) -> bool { + let axis = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "ROWS" | "COLUMNS"); + let order_by = |positions: &[usize]| positions.contains(&index) && word.eq_ignore_ascii_case("KEEP"); + let blanks = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "DEFAULT" | "FIRST" | "LAST"); + let reset = + |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "NONE" | "LOWESTPARENT" | "HIGHESTPARENT"); + match function { + "COLLAPSE" | "EXPAND" | "COLLAPSEALL" | "EXPANDALL" => axis(&[0, 1]), + "FIRST" | "LAST" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]), + "PREVIOUS" | "NEXT" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]), + "MOVINGAVERAGE" => axis(&[3]) || order_by(&[4]) || blanks(&[5]) || reset(&[6]), + "RUNNINGSUM" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]), + "RANGE" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]), + _ => false, + } +} + +/// The enum words accepted by the window/relation clauses. Matching is case-insensitive, and an +/// identifier outside this set is left to normal name binding so typos still report an error. +const WINDOW_KEYWORDS: &[&str] = &["ASC", "DESC", "ABS", "REL", "DEFAULT", "FIRST", "LAST", "KEEP", "NONE", "LOWESTPARENT", "HIGHESTPARENT"]; + +fn clause_keyword(expr: &Expr, allowed: &[&str]) -> Option { + let word = keyword_name(expr)?; + allowed.iter().any(|candidate| word.eq_ignore_ascii_case(candidate)).then_some(word) +} + +fn collect_measure_names(model: &DataModel, expr: &BoundExpr, out: &mut BTreeSet) { + match expr { + BoundExpr::Measure(index) => { + if let Some(measure) = model.measures.get(*index) { + out.insert(measure.name.clone()); + } + } + BoundExpr::Call { args, .. } | BoundExpr::TableConstructor(args) | BoundExpr::Tuple(args) => { + for arg in args { + collect_measure_names(model, arg, out); + } + } + BoundExpr::Unary { expr, .. } => collect_measure_names(model, expr, out), + BoundExpr::Binary { left, right, .. } => { + collect_measure_names(model, left, out); + collect_measure_names(model, right, out); + } + BoundExpr::VarReturn { vars, body } => { + for var in vars { + collect_measure_names(model, &var.expr, out); + } + collect_measure_names(model, body, out); + } + BoundExpr::Literal(_) + | BoundExpr::Column { .. } + | BoundExpr::UnqualifiedColumn { .. } + | BoundExpr::Table(_) + | BoundExpr::Variable { .. } + | BoundExpr::Keyword(_) => {} + } +} + +/// Parses and binds one measure formula against a model, without requiring a full model parse. +pub fn bind_formula(model: &DataModel, formula: &str) -> Result { + let expr = parse_expression(formula).map_err(|error| BindError::new(error.message, error.span))?; + Binder::new(model).bind_expression(&expr) +} diff --git a/crates/dax/src/model.rs b/crates/dax/src/model.rs new file mode 100644 index 000000000..b1c4eaf74 --- /dev/null +++ b/crates/dax/src/model.rs @@ -0,0 +1,371 @@ +//! Tabular data-model metadata: tables, columns, relationships and measures. +//! +//! This is the binder/evaluator's model view. It deliberately does not implement XLSX storage: +//! callers load the metadata from JSON or from a workbook adapter and parse the measure formulas +//! with [`DataModel::parse_formulas`]. Rows are not part of this layer; the evaluator supplies +//! table values. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::value::Scalar; +use crate::{Expr, ParseError, parse_expression}; + +/// A table in the model. Column order is preserved because `RELATEDTABLE`, `ROW` and table +/// constructors expose it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ModelTable { + pub name: String, + #[serde(default)] + pub columns: Vec, + /// Optional inline rows. Workbook adapters can fill these; the metadata-only binder ignores + /// them. Each row has one scalar per column, in column order. + #[serde(default)] + pub rows: Vec>, +} + +/// A model column. `data_type` is the model's declared type name (`Int64`, `Double`, `String`, +/// `DateTime`, `Boolean`, `Decimal`, ...); it is metadata, not a parsed [`crate::types::DataType`], +/// because model type names and DAX expression types are not the same vocabulary. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ModelColumn { + pub name: String, + #[serde(default)] + pub data_type: Option, +} + +/// Model metadata the binder does not need: hidden columns, the marked date column and each +/// column's default summarization. It travels inside the same model JSON document, on the table +/// and column objects (`"date_column"`, `"hidden"`, `"summarize_by"`), so a model stays one file; +/// the engine reads and validates it at the model boundary (`dataModel.load`) and reports it from +/// `dataModel.status`. +/// +/// The type doubles as the loader: unknown document keys (`rows`, `data_type`, `relationships`, +/// `measures`, ...) are ignored, so a document written before these fields existed loads with +/// every field at its default. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ModelMetadata { + pub tables: Vec, +} + +/// One table's metadata slice of a model document. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct TableMetadata { + pub name: String, + /// The column marked as this table's date column, in the model's spelling. + #[serde(skip_serializing_if = "Option::is_none")] + pub date_column: Option, + pub columns: Vec, +} + +/// One column's metadata slice of a model document. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ColumnMetadata { + pub name: String, + /// Hidden from the Data View and the field list (`dataModel.setColumnHidden`). Model + /// metadata, as in Excel; the window's "Show Hidden" toggle is only a view setting. + #[serde(skip_serializing_if = "is_false")] + pub hidden: bool, + /// Excel's "Summarize By" (`Sum`, `Average`, `Count`, `Min`, `Max`, `None`), canonicalized. + /// Absent falls back to the type default: numbers sum, everything else counts. + #[serde(skip_serializing_if = "Option::is_none")] + pub summarize_by: Option, +} + +/// The canonical spelling of a `Summarize By` name, or `None` when it is not one. Names match +/// case-insensitively and ignore spaces, hyphens and underscores, so `"do not summarize"`, +/// `"DoNotSummarize"` and `"none"` all mean `None`. +pub fn summarize_by_name(name: &str) -> Option<&'static str> { + let key: String = name.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).collect::().to_ascii_lowercase(); + match key.as_str() { + "sum" => Some("Sum"), + "average" | "avg" => Some("Average"), + "count" => Some("Count"), + "min" | "minimum" => Some("Min"), + "max" | "maximum" => Some("Max"), + "none" | "donotsummarize" => Some("None"), + _ => None, + } +} + +/// Whether a serde field should be left out of the serialized JSON (its default). +fn is_false(value: &bool) -> bool { + !*value +} + +impl ModelMetadata { + /// Parses and validates the metadata of a model JSON document. + /// + /// The type itself is the loader: unknown document keys (`rows`, `data_type`, + /// `relationships`, `measures`, ...) are ignored, so a document written before the metadata + /// fields existed yields every table and column with default metadata. + pub fn from_model_json(text: &str) -> Result { + let mut metadata: ModelMetadata = serde_json::from_str(text).map_err(|error| ModelError::new(format!("invalid model JSON: {error}")))?; + metadata.validate()?; + Ok(metadata) + } + + /// Canonicalizes the names and rejects unknown summarizations and a date column that is not + /// one of its table's columns. Duplicate table/column names are the [`DataModel`]'s check; + /// they are rejected here too so a document cannot produce an ambiguous lookup. + pub fn validate(&mut self) -> Result<(), ModelError> { + let mut tables = BTreeMap::new(); + for table in &mut self.tables { + if tables.insert(table.name.to_ascii_lowercase(), ()).is_some() { + return Err(ModelError::new(format!("duplicate model table `{}`", table.name))); + } + let mut columns = BTreeMap::new(); + for column in &mut table.columns { + if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() { + return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name))); + } + if let Some(name) = column.summarize_by.clone() { + let Some(canonical) = summarize_by_name(&name) else { + return Err(ModelError::new(format!("column `{}` has unknown summarization `{name}`", column.name))); + }; + column.summarize_by = Some(canonical.to_string()); + } + } + if let Some(date) = table.date_column.clone() { + let Some(column) = table.columns.iter().find(|column| column.name.eq_ignore_ascii_case(&date)) else { + return Err(ModelError::new(format!("table `{}` marks unknown column `{date}` as its date column", table.name))); + }; + table.date_column = Some(column.name.clone()); + } + } + Ok(()) + } + + /// A table's metadata, matching names case-insensitively. + pub fn table(&self, name: &str) -> Option<&TableMetadata> { + self.tables.iter().find(|table| table.name.eq_ignore_ascii_case(name)) + } + + /// A table's metadata for editing. + pub fn table_mut(&mut self, name: &str) -> Option<&mut TableMetadata> { + self.tables.iter_mut().find(|table| table.name.eq_ignore_ascii_case(name)) + } + + /// A column's metadata, matching table and column names case-insensitively. + pub fn column(&self, table: &str, column: &str) -> Option<&ColumnMetadata> { + self.table(table)?.columns.iter().find(|entry| entry.name.eq_ignore_ascii_case(column)) + } + + /// A column's metadata for editing. + pub fn column_mut(&mut self, table: &str, column: &str) -> Option<&mut ColumnMetadata> { + let table = self.table_mut(table)?; + table.columns.iter_mut().find(|entry| entry.name.eq_ignore_ascii_case(column)) + } +} + +/// A single-column relationship between two model tables. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Relationship { + pub from_table: String, + pub from_column: String, + pub to_table: String, + pub to_column: String, + /// `true` when the relationship filters in both directions. + #[serde(default)] + pub bidirectional: bool, + /// Inactive relationships can be activated by `USERELATIONSHIP`. + #[serde(default)] + pub inactive: bool, +} + +/// A measure definition. The formula is DAX text; [`DataModel::parse_formulas`] parses it into +/// [`Measure::expr`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Measure { + pub name: String, + pub formula: String, + /// The home table, used by `COUNTROWS()` without an argument and for field-list placement. + #[serde(default)] + pub table: Option, + #[serde(default)] + pub format: Option, + #[serde(skip)] + pub expr: Option, +} + +/// A model definition loaded from JSON or another workbook adapter. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct DataModel { + #[serde(default)] + pub tables: Vec, + #[serde(default)] + pub relationships: Vec, + #[serde(default)] + pub measures: Vec, +} + +/// A metadata or formula error found while preparing a model for binding. +#[derive(Clone, Debug, PartialEq, thiserror::Error)] +#[error("{message}")] +pub struct ModelError { + pub message: String, +} + +impl ModelError { + fn new(message: impl Into) -> Self { + ModelError { message: message.into() } + } +} + +impl DataModel { + /// Parses every measure formula and validates table/column/relationship names. + /// + /// Names are compared case-insensitively. Duplicate table names, duplicate column names + /// within a table, and relationships naming missing tables/columns are rejected. + pub fn parse_formulas(&mut self) -> Result<(), ModelError> { + let mut tables: BTreeMap = BTreeMap::new(); + for (index, table) in self.tables.iter().enumerate() { + let key = table.name.to_ascii_lowercase(); + if tables.insert(key, index).is_some() { + return Err(ModelError::new(format!("duplicate model table `{}`", table.name))); + } + let mut columns = BTreeMap::new(); + for column in &table.columns { + if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() { + return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name))); + } + } + } + + for relationship in &self.relationships { + self.require_column(&relationship.from_table, &relationship.from_column)?; + self.require_column(&relationship.to_table, &relationship.to_column)?; + } + + let mut names = BTreeMap::new(); + for measure in &mut self.measures { + // Measure names are compared case-insensitively everywhere else, so a duplicate would + // silently hide the second formula. + if names.insert(measure.name.to_ascii_lowercase(), ()).is_some() { + return Err(ModelError::new(format!("duplicate measure `{}`", measure.name))); + } + let expr = parse_expression(&measure.formula).map_err(|error| ModelError::new(format!("measure `{}`: {error}", measure.name)))?; + measure.expr = Some(expr); + } + Ok(()) + } + + /// The index of a table, ignoring case. + pub fn table_index(&self, name: &str) -> Option { + self.tables.iter().position(|table| table.name.eq_ignore_ascii_case(name)) + } + + /// The index of a column within a table, ignoring case. + pub fn column_index(&self, table: usize, name: &str) -> Option { + self.tables.get(table)?.columns.iter().position(|column| column.name.eq_ignore_ascii_case(name)) + } + + /// The index of a measure, ignoring case. + pub fn measure_index(&self, name: &str) -> Option { + self.measures.iter().position(|measure| measure.name.eq_ignore_ascii_case(name)) + } + + /// Tables that contain a column with this name. + pub fn tables_with_column(&self, name: &str) -> Vec { + self.tables + .iter() + .enumerate() + .filter(|(_, table)| table.columns.iter().any(|column| column.name.eq_ignore_ascii_case(name))) + .map(|(index, _)| index) + .collect() + } + + fn require_column(&self, table: &str, column: &str) -> Result<(), ModelError> { + let Some(table_index) = self.table_index(table) else { + return Err(ModelError::new(format!("relationship names missing table `{table}`"))); + }; + if self.column_index(table_index, column).is_none() { + return Err(ModelError::new(format!("relationship names missing column `{column}` in table `{table}`"))); + } + Ok(()) + } +} + +/// The result of [`parse_expression`] for a measure, used by callers that want to surface the +/// parse error separately from the model metadata. +pub fn parse_measure(formula: &str) -> Result { + parse_expression(formula) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The model JSON `docs/power-pivot.md` documents, written before the metadata fields existed. + /// It must keep loading (the metadata parser ignores everything it does not own), and adding + /// the fields must not change what the document means. + const OLD_SCHEMA: &str = r#"{ + "tables": [{"name":"Sales","columns":[{"name":"Region","data_type":"String"},{"name":"Amount","data_type":"Double"}], + "rows":[["East",10],["West",20]]}], + "relationships": [], + "measures": [{"name":"Total Sales","formula":"SUM(Sales[Amount])","table":"Sales"}] + }"#; + + #[test] + fn old_schema_json_loads_with_default_metadata() { + let mut model: DataModel = serde_json::from_str(OLD_SCHEMA).expect("old model JSON loads"); + model.parse_formulas().expect("old model JSON validates"); + assert_eq!(model.tables[0].columns.len(), 2, "unknown metadata keys never disturb the model"); + + let metadata = ModelMetadata::from_model_json(OLD_SCHEMA).expect("old model JSON has valid metadata"); + let table = metadata.table("sales").expect("the table is in the metadata"); + assert_eq!(table.date_column, None); + assert!(!metadata.column("Sales", "amount").expect("column metadata").hidden); + assert_eq!(metadata.column("Sales", "Amount").and_then(|column| column.summarize_by.clone()), None); + + let written = serde_json::to_value(&metadata).expect("metadata serializes"); + assert!(written["tables"][0].get("date_column").is_none(), "an unmarked table writes no date column: {written}"); + assert!(written["tables"][0]["columns"][0].get("hidden").is_none(), "a visible column writes no hidden flag: {written}"); + assert!(written["tables"][0]["columns"][0].get("summarize_by").is_none(), "an absent summarization stays absent: {written}"); + let reloaded = ModelMetadata::from_model_json(&written.to_string()).expect("the written metadata reloads"); + assert_eq!(reloaded, metadata); + } + + #[test] + fn new_metadata_is_read_from_the_model_document() { + let json = r#"{ + "tables": [{"name":"Calendar","date_column":"date", + "columns":[{"name":"Date","data_type":"DateTime"},{"name":"Secret","hidden":true,"summarize_by":"do not summarize"}], + "rows":[[45292,null]]}], + "relationships": [], + "measures": [] + }"#; + let mut model: DataModel = serde_json::from_str(json).expect("JSON with metadata loads"); + model.parse_formulas().expect("the model validates"); + let metadata = ModelMetadata::from_model_json(json).expect("the metadata validates"); + let table = metadata.table("Calendar").expect("a table"); + assert_eq!(table.date_column.as_deref(), Some("Date"), "the stored name takes the column's spelling"); + let secret = metadata.column("calendar", "SECRET").expect("column metadata"); + assert!(secret.hidden); + assert_eq!(secret.summarize_by.as_deref(), Some("None"), "the summarization is canonicalized"); + } + + #[test] + fn metadata_naming_missing_columns_or_aggregates_is_rejected() { + let bad_date = r#"{"tables":[{"name":"T","columns":[{"name":"A"}],"rows":[],"date_column":"Missing"}]}"#; + assert!(ModelMetadata::from_model_json(bad_date).is_err(), "a date column that is not a column is rejected"); + + let bad_summary = r#"{"tables":[{"name":"T","columns":[{"name":"A","summarize_by":"median"}],"rows":[]}]}"#; + assert!(ModelMetadata::from_model_json(bad_summary).is_err(), "an unknown summarization is rejected"); + + let duplicate = r#"{"tables":[{"name":"T","columns":[{"name":"A"},{"name":"a"}]}]}"#; + assert!(ModelMetadata::from_model_json(duplicate).is_err(), "ambiguous column names are rejected"); + } + + #[test] + fn summarize_by_names_match_loosely() { + assert_eq!(summarize_by_name("SUM"), Some("Sum")); + assert_eq!(summarize_by_name("average"), Some("Average")); + assert_eq!(summarize_by_name("Do Not Summarize"), Some("None")); + assert_eq!(summarize_by_name("median"), None); + } +} diff --git a/crates/dax/src/types.rs b/crates/dax/src/types.rs new file mode 100644 index 000000000..128334049 --- /dev/null +++ b/crates/dax/src/types.rs @@ -0,0 +1,732 @@ +//! 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, + } +} + +/// A scalar operand's type: a table-valued call may still resolve to a single row/column at +/// evaluation time (`LASTDATE('Date'[Date]) - 1`), so it is unknown here rather than a table. +fn scalar_operand(expr: &Expr) -> Result { + let inferred = infer_type(expr)?; + Ok(if inferred == InferredType::Table && matches!(&expr.kind, ExprKind::Call(_)) { InferredType::Unknown } else { inferred }) +} + +/// Infers the static type of an expression. +/// +/// Name references are [`InferredType::Unknown`] (they need the model). Catalogued calls take +/// their documented [`crate::functions::ReturnType`]; unknown functions and `Any`/`Numeric` +/// return types stay unknown. Incompatible known operands produce a [`TypeError`]. +pub fn infer_type(expr: &Expr) -> Result { + match &expr.kind { + ExprKind::Literal(literal) => Ok(InferredType::Data(literal_type(literal))), + ExprKind::Name(_) => Ok(InferredType::Unknown), + ExprKind::Call(call) => { + // The call itself may be unknown without a signature catalog, but every argument + // still has to type-check. + for arg in &call.args { + infer_type(arg)?; + } + Ok(call_type(call)) + } + ExprKind::Unary { op, expr } => { + let operand = scalar_operand(expr)?; + unary_type(*op, operand) + } + ExprKind::Binary { op, left, right } => { + // `(a, b) IN { (a, b), ... }` uses a row constructor on the left, not a table + // expression. Validate its elements but let the operator comparison handle the + // row value. + let left = match (&left.kind, op) { + (ExprKind::Tuple(items), BinaryOp::In) => { + for item in items { + infer_type(item)?; + } + InferredType::Unknown + } + _ if *op == BinaryOp::In => infer_type(left)?, + _ => scalar_operand(left)?, + }; + let right = if *op == BinaryOp::In { infer_type(right)? } else { scalar_operand(right)? }; + binary_type(*op, left, right) + } + ExprKind::Table(items) | ExprKind::Tuple(items) => { + // Containers are tables, but their elements still have to type-check. + for item in items { + infer_type(item)?; + } + Ok(InferredType::Table) + } + // Variable references are names, so their values are unknown without an environment; the + // block's type is the type of its `RETURN` expression. Every declaration still has to + // type-check, even when the body does not use it. + ExprKind::VarReturn { vars, body } => { + for var in vars { + infer_type(&var.expr)?; + } + infer_type(body) + } + } +} + +/// The documented return type of a catalogued function, mapped onto the static type model. +/// +/// `Numeric` stays [`InferredType::Unknown`] because its concrete type (Integer, Currency or +/// Decimal) follows the inputs; `Any`/unknown signatures stay unknown as well. +fn call_type(call: &Call) -> InferredType { + if call.args.is_empty() { + if call.name.text.eq_ignore_ascii_case("TRUE") || call.name.text.eq_ignore_ascii_case("FALSE") { + return InferredType::Data(DataType::Boolean); + } + if call.name.text.eq_ignore_ascii_case("BLANK") { + return InferredType::Blank; + } + } + let Some(spec) = crate::functions::lookup(&call.name.text) else { + return InferredType::Unknown; + }; + match spec.return_type { + crate::functions::ReturnType::Integer => InferredType::Data(DataType::Integer), + crate::functions::ReturnType::Decimal => InferredType::Data(DataType::Decimal), + crate::functions::ReturnType::Numeric => InferredType::Unknown, + crate::functions::ReturnType::Currency => InferredType::Data(DataType::Currency), + crate::functions::ReturnType::Boolean => InferredType::Data(DataType::Boolean), + crate::functions::ReturnType::DateTime => InferredType::Data(DataType::DateTime), + crate::functions::ReturnType::String => InferredType::Data(DataType::String), + crate::functions::ReturnType::Variant => InferredType::Data(DataType::Variant), + crate::functions::ReturnType::Table => InferredType::Table, + crate::functions::ReturnType::Blank => InferredType::Blank, + crate::functions::ReturnType::Any => InferredType::Unknown, + } +} + +/// Infers the result type of a unary operator. `+` and `-` preserve the numeric type (DateTime +/// keeps its serial type); `NOT` always yields Boolean. A BLANK operand stays polymorphic +/// instead of becoming Integer. +pub fn unary_type(op: UnaryOp, operand: InferredType) -> Result { + 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 000000000..60efa2c94 --- /dev/null +++ b/crates/dax/src/validate.rs @@ -0,0 +1,185 @@ +//! 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 function catalog. +/// +/// Returns every error the call contains, or an empty vector for a valid call and for a function +/// that is not in the catalog. Because [`Call`] does not carry its own span, arity errors use +/// [`Span::empty`]; use [`validate_expression`] when spans matter. +pub fn validate_call(call: &Call) -> Vec { + 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.matches(arity)).collect(); + if matching.is_empty() { + return vec![arity_error(spec, arity, call_span)]; + } + let mut errors = Vec::new(); + for (index, argument) in call.args.iter().enumerate() { + if matching.iter().any(|overload| overload_accepts(overload, index, argument)) { + continue; + } + let expected = expected_kinds(&matching, index); + errors.push(ValidationError { + function: spec.name, + kind: ValidationErrorKind::ArgumentKind, + message: format!("{} argument {} must be {expected}, found {}", spec.name, index + 1, describe_argument(argument)), + span: argument.span, + }); + } + errors +} + +fn arity_error(spec: &FunctionSpec, arity: usize, span: Span) -> ValidationError { + let expected = if spec.min_args == spec.max_args { format!("{}", spec.min_args) } else { format!("{} to {}", spec.min_args, spec.max_args) }; + ValidationError { + function: spec.name, + kind: ValidationErrorKind::Arity, + message: format!("{} expects {expected} argument(s), found {arity}", spec.name), + span, + } +} + +fn overload_accepts(overload: &Overload, index: usize, argument: &Expr) -> bool { + match overload.kind_at(index) { + Some(kind) => accepts(kind, argument), + None => true, + } +} + +fn expected_kinds(overloads: &[&Overload], index: usize) -> String { + let mut expected: Vec<&'static str> = Vec::new(); + for overload in overloads { + let Some(kind) = overload.kind_at(index) else { + continue; + }; + let description = kind.description(); + if !expected.contains(&description) { + expected.push(description); + } + } + expected.join(" or ") +} + +/// The only argument checks that are decidable without a model. +fn accepts(kind: ParamKind, argument: &Expr) -> bool { + match kind { + ParamKind::Column => is_column_reference(argument), + ParamKind::Table => !is_obvious_scalar(argument) && !is_column_reference(argument), + ParamKind::Expression + | ParamKind::Scalar + | ParamKind::Logical + | ParamKind::Any + | ParamKind::Date + | ParamKind::Text + | ParamKind::Number + | ParamKind::Boolean + | ParamKind::Function + | ParamKind::Reference + | ParamKind::Json + | ParamKind::Variant => true, + } +} + +fn is_column_reference(expr: &Expr) -> bool { + matches!( + &expr.kind, + ExprKind::Name(name_ref) if name_ref.name.style == NameStyle::Bracketed + ) +} + +/// Literals and operator expressions are certainly scalars, never tables. Names, calls, table +/// constructors and row constructors may be dynamic table expressions, so they are not rejected. +fn is_obvious_scalar(expr: &Expr) -> bool { + matches!(&expr.kind, ExprKind::Literal(_) | ExprKind::Unary { .. } | ExprKind::Binary { .. }) +} + +fn describe_argument(expr: &Expr) -> &'static str { + match &expr.kind { + ExprKind::Literal(_) => "a literal", + ExprKind::Name(_) => "a name reference", + ExprKind::Call(_) => "a function call", + ExprKind::Unary { .. } | ExprKind::Binary { .. } => "an operator expression", + ExprKind::Table(_) => "a table constructor", + ExprKind::Tuple(_) => "a row constructor", + ExprKind::VarReturn { .. } => "a VAR/RETURN expression", + } +} diff --git a/crates/dax/tests/aggregation.rs b/crates/dax/tests/aggregation.rs new file mode 100644 index 000000000..de2e01c07 --- /dev/null +++ b/crates/dax/tests/aggregation.rs @@ -0,0 +1,532 @@ +//! Integration tests for the aggregation catalog and its static validation. + +use gridcraft_dax::functions::{BlankPolicy, FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog, lookup}; +use gridcraft_dax::{Expr, ExprKind, ValidationError, ValidationErrorKind, parse_expression, validate_call, validate_expression}; + +fn aggregation_catalog() -> Vec<&'static FunctionSpec> { + catalog().iter().filter(|spec| spec.category == FunctionCategory::Aggregation).collect() +} + +const FUNCTIONS: [(&str, usize, usize); 22] = [ + ("APPROXIMATEDISTINCTCOUNT", 1, 1), + ("AVERAGE", 1, 1), + ("AVERAGEA", 1, 1), + ("AVERAGEX", 2, 2), + ("COUNT", 1, 1), + ("COUNTA", 1, 1), + ("COUNTAX", 2, 2), + ("COUNTBLANK", 1, 1), + ("COUNTROWS", 0, 1), + ("COUNTX", 2, 2), + ("DISTINCTCOUNT", 1, 1), + ("DISTINCTCOUNTNOBLANK", 1, 1), + ("MAX", 1, 2), + ("MAXA", 1, 1), + ("MAXX", 2, 3), + ("MIN", 1, 2), + ("MINA", 1, 1), + ("MINX", 2, 3), + ("PRODUCT", 1, 1), + ("PRODUCTX", 2, 2), + ("SUM", 1, 1), + ("SUMX", 2, 2), +]; + +fn parse(src: &str) -> Expr { + match parse_expression(src) { + Ok(expr) => expr, + Err(error) => panic!("{src:?} did not parse: {error}"), + } +} + +fn spec(name: &str) -> &'static FunctionSpec { + match lookup(name) { + Some(spec) => spec, + None => panic!("{name} is missing from the catalog"), + } +} + +fn expression_errors(src: &str) -> Vec { + 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 = aggregation_catalog(); + assert_eq!(specs.len(), FUNCTIONS.len()); + + for (name, min_args, max_args) in FUNCTIONS { + let matches: Vec<&FunctionSpec> = specs.iter().copied().filter(|spec| spec.name == name).collect(); + assert_eq!(matches.len(), 1, "{name} should appear exactly once"); + assert_eq!(matches[0].min_args, min_args, "{name} min arity"); + assert_eq!(matches[0].max_args, max_args, "{name} max arity"); + assert_eq!(matches[0].category, FunctionCategory::Aggregation); + } + + let catalogued: std::collections::BTreeSet<&str> = specs.iter().map(|spec| spec.name).collect(); + let documented: std::collections::BTreeSet<&str> = FUNCTIONS.iter().map(|(name, _, _)| *name).collect(); + assert_eq!(catalogued, documented); +} + +#[test] +fn lookup_is_case_insensitive() { + for (name, _, _) in FUNCTIONS { + assert_eq!(lookup(name).map(|spec| spec.name), Some(name)); + assert_eq!(lookup(&name.to_ascii_lowercase()).map(|spec| spec.name), Some(name)); + assert_eq!(lookup(&name.to_ascii_uppercase()).map(|spec| spec.name), Some(name)); + } + assert_eq!(lookup("SuM").map(|spec| spec.name), Some("SUM")); + assert!(lookup("SUMM").is_none()); + assert!(lookup("").is_none()); + assert!(lookup("SUM ").is_none()); +} + +#[test] +fn every_record_has_consistent_signature_and_metadata() { + for spec in aggregation_catalog() { + assert!(!spec.description.is_empty(), "{} description", spec.name); + assert!(!spec.examples.is_empty(), "{} examples", spec.name); + assert_eq!(spec.params.len(), spec.max_args, "{} descriptive params", spec.name); + + let required = spec.params.iter().filter(|param| !param.optional).count(); + let optional = spec.params.iter().filter(|param| param.optional).count(); + assert_eq!(required, spec.min_args, "{} required params", spec.name); + assert_eq!(optional, spec.max_args - spec.min_args, "{} optional params", spec.name); + + assert!(!spec.overloads.is_empty(), "{} overloads", spec.name); + for arity in spec.min_args..=spec.max_args { + assert!(spec.overload_for(arity).is_some(), "{} has no overload for arity {arity}", spec.name); + } + let arities: Vec = spec.overloads.iter().map(|overload| overload.arity()).collect(); + assert_eq!(arities.iter().min().copied(), Some(spec.min_args), "{} overload min", spec.name); + assert_eq!(arities.iter().max().copied(), Some(spec.max_args), "{} overload max", spec.name); + + if let Some(target) = spec.sugar_of { + assert_ne!(target, spec.name, "{} is sugar of itself", spec.name); + assert!(lookup(target).is_some(), "{} sugar target {target} is missing", spec.name); + } + } +} + +#[test] +fn iterator_and_sugar_metadata() { + let iterators = ["AVERAGEX", "COUNTAX", "COUNTX", "MAXX", "MINX", "PRODUCTX", "SUMX"]; + for spec in aggregation_catalog() { + assert_eq!(spec.flags.iterator, iterators.contains(&spec.name), "{} iterator flag", spec.name); + assert_eq!(spec.is_iterator(), spec.flags.iterator, "{} is_iterator", spec.name); + } + + for (name, target) in [ + ("AVERAGE", "AVERAGEX"), + ("COUNT", "COUNTX"), + ("COUNTA", "COUNTAX"), + ("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 aggregation_catalog() { + if spec.name != "APPROXIMATEDISTINCTCOUNT" && spec.name != "DISTINCTCOUNTNOBLANK" { + assert!(spec.flags.excel_compatible, "{} should be Excel compatible", spec.name); + } + assert!(spec.flags.direct_query_limited, "{} DirectQuery note", spec.name); + } + + let not_recommended: Vec<&str> = aggregation_catalog().iter().filter(|spec| spec.flags.not_recommended).map(|spec| spec.name).collect(); + assert_eq!(not_recommended, ["AVERAGEA"]); + + // COUNTROWS () is in the catalog even though Excel's embedded engine rejects that form. + assert_valid("COUNTROWS ( )"); + assert_eq!(spec("COUNTROWS").min_args, 0); +} + +#[test] +fn overloads_model_the_documented_signatures() { + assert_eq!(overload_kinds(spec("MAX"), 1), Some(vec![ParamKind::Column])); + assert_eq!(overload_kinds(spec("MAX"), 2), Some(vec![ParamKind::Scalar, ParamKind::Scalar])); + assert_eq!(overload_kinds(spec("MIN"), 1), Some(vec![ParamKind::Column])); + assert_eq!(overload_kinds(spec("MIN"), 2), Some(vec![ParamKind::Scalar, ParamKind::Scalar])); + assert_eq!(overload_kinds(spec("COUNTROWS"), 0), Some(Vec::new())); + assert_eq!(overload_kinds(spec("COUNTROWS"), 1), Some(vec![ParamKind::Table])); + assert_eq!(overload_kinds(spec("MAXX"), 2), Some(vec![ParamKind::Table, ParamKind::Expression])); + assert_eq!(overload_kinds(spec("MAXX"), 3), Some(vec![ParamKind::Table, ParamKind::Expression, ParamKind::Logical])); + assert_eq!(overload_kinds(spec("MINX"), 3), Some(vec![ParamKind::Table, ParamKind::Expression, ParamKind::Logical])); + + let maxx = spec("MAXX"); + assert_eq!(maxx.params.len(), 3); + assert_eq!(maxx.params[2].name, "Variant"); + assert_eq!(maxx.params[2].kind, ParamKind::Logical); + assert!(maxx.params[2].optional); +} + +#[test] +fn arity_boundaries_accept_and_reject_the_right_calls() { + for src in [ + "SUM ( Sales[Amount] )", + "COUNTROWS ( )", + "COUNTROWS ( Sales )", + "MAX ( 1, 2 )", + "MAX ( Sales[Amount] )", + "MIN ( 3, 5 )", + "MAXX ( Sales, Sales[Amount] )", + "MAXX ( Sales, Sales[Amount], TRUE )", + "MINX ( Sales, Sales[Amount] )", + "MINX ( Sales, Sales[Amount], FALSE )", + "AVERAGEX ( Sales, Sales[Amount] )", + "COUNTAX ( Sales, Sales[Flag] )", + "COUNTX ( Sales, Sales[Quantity] )", + "PRODUCTX ( Sales, Sales[Quantity] )", + "SUMX ( Sales, Sales[Amount] )", + "DISTINCTCOUNT ( Sales[Region] )", + ] { + assert_valid(src); + } + + for src in [ + "SUM ( )", + "SUM ( Sales[Amount], Sales[Amount] )", + "COUNTROWS ( Sales, Sales )", + "MAX ( )", + "MAX ( 1, 2, 3 )", + "MIN ( 1, 2, 3 )", + "MAXX ( Sales )", + "MAXX ( Sales, Sales[Amount], TRUE, FALSE )", + "MINX ( Sales )", + "MINX ( Sales, Sales[Amount], TRUE, FALSE )", + "AVERAGEX ( Sales )", + "AVERAGEX ( Sales, Sales[Amount], TRUE )", + "COUNTAX ( Sales )", + "COUNTX ( Sales )", + "PRODUCTX ( Sales )", + "SUMX ( Sales )", + "DISTINCTCOUNT ( )", + "COUNT ( )", + ] { + let errors = assert_invalid_kind(src, ValidationErrorKind::Arity); + assert_eq!(errors.len(), 1, "{src:?} should report exactly one arity error: {errors:?}"); + } +} + +#[test] +fn every_documented_arity_boundary_is_enforced() { + for spec in aggregation_catalog() { + for arity in 0..=4usize { + let arguments = vec!["1"; arity].join(", "); + let src = format!("{} ( {arguments} )", spec.name); + let errors = expression_errors(&src); + let arity_errors: Vec<&ValidationError> = errors.iter().filter(|error| error.kind == ValidationErrorKind::Arity).collect(); + if arity < spec.min_args || arity > spec.max_args { + assert_eq!(arity_errors.len(), 1, "{src:?} should report one arity error: {errors:?}"); + } else { + assert!(arity_errors.is_empty(), "{src:?} has a documented overload and must not report an arity error: {errors:?}"); + } + } + } +} + +#[test] +fn column_only_arguments_must_be_bracketed_references() { + for src in [ + "SUM ( 1 )", + "AVERAGE ( 1 + 1 )", + "COUNT ( \"x\" )", + "COUNTA ( TRUE )", + "COUNTBLANK ( 1 )", + "DISTINCTCOUNT ( 1 )", + "DISTINCTCOUNTNOBLANK ( 1 )", + "APPROXIMATEDISTINCTCOUNT ( 1 )", + "PRODUCT ( 1 )", + "MAXA ( 1 )", + "MINA ( 1 )", + "MAX ( 1 )", + "MIN ( 1 )", + "SUM ( -1 )", + ] { + assert_invalid_kind(src, ValidationErrorKind::ArgumentKind); + } + + for src in [ + "SUM ( Sales[Amount] )", + "SUM ( [Amount] )", + "AVERAGE ( 'Sales'[Amount] )", + "COUNT ( Sales[Text] )", + "DISTINCTCOUNT ( Sales[Region] )", + "APPROXIMATEDISTINCTCOUNT ( Sales[ProductKey] )", + "PRODUCT ( Sales[Quantity] )", + "MAX ( Sales[Amount] )", + "MIN ( Sales[Amount] )", + "MAXA ( Sales[Flag] )", + "MINA ( Sales[Flag] )", + ] { + assert_valid(src); + } + + let errors = assert_invalid_kind("SUM ( 1 )", ValidationErrorKind::ArgumentKind); + let message = &errors[0].message; + assert!(message.contains("SUM"), "{message}"); + assert!(message.contains("column reference"), "{message}"); + assert!(message.contains("literal"), "{message}"); +} + +#[test] +fn table_arguments_reject_obvious_scalars_but_accept_dynamic_tables() { + for src in [ + "COUNTROWS ( 1 )", + "COUNTROWS ( \"Sales\" )", + "COUNTROWS ( -1 )", + "COUNTROWS ( 1 + 1 )", + "COUNTROWS ( Sales[Amount] )", + "SUMX ( 1, Sales[Amount] )", + "AVERAGEX ( 1 + 1, Sales[Amount] )", + "MAXX ( TRUE, Sales[Amount] )", + "MINX ( 2 * 2, Sales[Amount] )", + "COUNTAX ( \"x\", Sales[Flag] )", + "COUNTX ( FALSE, Sales[Quantity] )", + ] { + assert_invalid_kind(src, ValidationErrorKind::ArgumentKind); + } + + for src in [ + "COUNTROWS ( Sales )", + "COUNTROWS ( DISTINCT ( Sales[Region] ) )", + "COUNTROWS ( VALUES ( Sales[Region] ) )", + "COUNTROWS ( FILTER ( Sales, Sales[Amount] > 0 ) )", + "COUNTROWS ( { 1, 2 } )", + "SUMX ( FILTER ( Sales, Sales[Amount] > 0 ), Sales[Amount] )", + "SUMX ( { 1, 2, 3 }, [Value] )", + "AVERAGEX ( ALL ( Sales ), [Amount] )", + "MAXX ( Sales, Sales[Amount] )", + "MINX ( RELATEDTABLE ( ResellerSales ), [Sales Amount] )", + ] { + assert_valid(src); + } +} + +#[test] +fn max_and_min_model_both_overloads() { + assert_valid("MAX ( 1, 2 )"); + assert_valid("MAX ( 3, 5 )"); + assert_valid("MAX ( Sales[Amount] )"); + assert_valid("MAX ( 10000, [Sales Amount] )"); + assert_valid("MIN ( 3, 5 )"); + assert_valid("MIN ( Sales[Net Price] )"); + assert_valid("MIN ( 5000000, [Sales Amount] )"); + + // One argument is the column-only overload, not a scalar. + assert_invalid_kind("MAX ( 1 )", ValidationErrorKind::ArgumentKind); + assert_invalid_kind("MIN ( 1 )", ValidationErrorKind::ArgumentKind); + + // Three arguments match no overload. + assert_invalid_kind("MAX ( 1, 2, 3 )", ValidationErrorKind::Arity); + assert_invalid_kind("MIN ( 1, 2, 3 )", ValidationErrorKind::Arity); +} + +#[test] +fn countrows_accepts_zero_or_one_table_argument() { + for src in ["COUNTROWS ( )", "COUNTROWS ( Sales )", "COUNTROWS ( DISTINCT ( Sales[Region] ) )"] { + assert_valid(src); + } + assert_invalid_kind("COUNTROWS ( Sales, Sales )", ValidationErrorKind::Arity); + assert_invalid_kind("COUNTROWS ( 1 )", ValidationErrorKind::ArgumentKind); + + let spec = spec("COUNTROWS"); + assert_eq!((spec.min_args, spec.max_args), (0, 1)); + assert_eq!(overload_kinds(spec, 0), Some(Vec::new())); + assert_eq!(overload_kinds(spec, 1), Some(vec![ParamKind::Table])); +} + +#[test] +fn maxx_and_minx_accept_the_optional_variant_argument() { + for src in [ + "MAXX ( Sales, Sales[Amount] )", + "MAXX ( Sales, Sales[Amount], TRUE )", + "MAXX ( Customer, 1 * Customer[LargeFamily] )", + "MINX ( Sales, Sales[Amount] )", + "MINX ( Sales, Sales[Amount], FALSE )", + "MINX ( Customer, 1 * Customer[NoCars] )", + ] { + assert_valid(src); + } + assert_invalid_kind("MAXX ( Sales )", ValidationErrorKind::Arity); + assert_invalid_kind("MAXX ( Sales, Sales[Amount], TRUE, FALSE )", ValidationErrorKind::Arity); + assert_invalid_kind("MINX ( Sales )", ValidationErrorKind::Arity); + assert_invalid_kind("MINX ( Sales, Sales[Amount], TRUE, FALSE )", ValidationErrorKind::Arity); +} + +#[test] +fn every_catalog_example_parses_and_validates() { + for spec in aggregation_catalog() { + assert!(!spec.examples.is_empty(), "{} has no examples", spec.name); + for example in spec.examples { + let expr = parse(example); + let errors = validate_expression(&expr); + assert!(errors.is_empty(), "{} example {example:?} should validate, got {errors:?}", spec.name); + } + } +} + +#[test] +fn unknown_functions_are_ignored_but_nested_calls_are_checked() { + assert!(expression_errors("FOO ( 1, 2, 3 )").is_empty()); + assert!(expression_errors("CALCULATE ( SUM ( Sales[Amount] ), Sales[Region] = \"East\" )").is_empty()); + assert!(call_errors("FOO ( 1, 2, 3 )").is_empty()); + + let errors = expression_errors("CALCULATE ( SUM ( 1 ) )"); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].function, "SUM"); + assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind); +} + +#[test] +fn validate_call_reports_arities_and_kinds() { + let errors = call_errors("MAX ( 1, 2, 3 )"); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].kind, ValidationErrorKind::Arity); + // `Call` has no own span; the expression validator supplies it. + assert!(errors[0].span.is_empty()); + + let errors = call_errors("SUM ( 1 )"); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind); + assert!(!errors[0].span.is_empty()); + + assert!(call_errors("SUM ( Sales[Amount] )").is_empty()); + assert!(call_errors("COUNTROWS ( )").is_empty()); +} + +#[test] +fn validate_expression_reports_every_error_with_a_span() { + let src = "SUM ( 1 ) + AVERAGE ( 2 ) + MAX ( 3 )"; + let errors = expression_errors(src); + assert_eq!(errors.len(), 3, "{errors:?}"); + for error in &errors { + assert!(!error.span.is_empty(), "{error:?}"); + assert!(error.span.end <= src.len(), "{error:?}"); + } + let arguments: Vec<&str> = errors.iter().map(|error| &src[error.span.start..error.span.end]).collect(); + assert_eq!(arguments, ["1", "2", "3"]); + + let src = "MAX ( 1, 2, 3 )"; + let errors = expression_errors(src); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].kind, ValidationErrorKind::Arity); + assert_eq!(&src[errors[0].span.start..errors[0].span.end], src); + + let src = "COUNTROWS ( 1 )"; + let errors = expression_errors(src); + assert_eq!(errors.len(), 1); + assert_eq!(&src[errors[0].span.start..errors[0].span.end], "1"); +} diff --git a/crates/dax/tests/binder.rs b/crates/dax/tests/binder.rs new file mode 100644 index 000000000..c40648d5e --- /dev/null +++ b/crates/dax/tests/binder.rs @@ -0,0 +1,205 @@ +//! Model metadata and name-binding tests. + +use gridcraft_dax::binder::{BoundExpr, BoundVariable}; +use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship}; +use gridcraft_dax::{Binder, parse_expression}; + +fn sample_model() -> DataModel { + let mut model = DataModel { + tables: vec![ + ModelTable { + name: "Sales".into(), + columns: vec![ + ModelColumn { name: "Region".into(), data_type: Some("String".into()) }, + ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }, + ], + rows: vec![], + }, + ModelTable { name: "Date".into(), columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }], rows: vec![] }, + ], + relationships: vec![Relationship { + from_table: "Sales".into(), + from_column: "Region".into(), + to_table: "Date".into(), + to_column: "Date".into(), + bidirectional: false, + inactive: false, + }], + measures: vec![ + Measure { name: "Total Sales".into(), formula: "SUM ( Sales[Amount] )".into(), table: Some("Sales".into()), format: None, expr: None }, + Measure { + name: "East Sales".into(), + formula: "CALCULATE ( [Total Sales], Sales[Region] = \"East\" )".into(), + table: Some("Sales".into()), + format: None, + expr: None, + }, + Measure { name: "Cycle A".into(), formula: "[Cycle B]".into(), table: None, format: None, expr: None }, + Measure { name: "Cycle B".into(), formula: "[Cycle A]".into(), table: None, format: None, expr: None }, + ], + }; + model.parse_formulas().expect("model parses"); + model +} + +fn bind(model: &DataModel, formula: &str) -> BoundExpr { + let expr = parse_expression(formula).expect("formula parses"); + Binder::new(model).bind_expression(&expr).expect("formula binds") +} + +#[test] +fn binds_qualified_columns_tables_and_measures() { + let model = sample_model(); + match bind(&model, "SUM ( Sales[Amount] )") { + BoundExpr::Call { spec, args } => { + assert_eq!(spec.name, "SUM"); + match &args[0] { + BoundExpr::Column { table, column } => { + assert_eq!(model.tables[*table].name, "Sales"); + assert_eq!(model.tables[*table].columns[*column].name, "Amount"); + } + other => panic!("expected column, got {other:?}"), + } + } + other => panic!("expected call, got {other:?}"), + } + assert!(matches!(bind(&model, "Sales"), BoundExpr::Table(0))); + assert!(matches!(bind(&model, "[Total Sales]"), BoundExpr::Measure(0))); + // A measure reference may carry its home table as a qualifier. + assert!(matches!(bind(&model, "Sales[Total Sales]"), BoundExpr::Measure(0))); + assert!(matches!(bind(&model, "[Amount]"), BoundExpr::UnqualifiedColumn { .. })); +} + +#[test] +fn reports_unknown_names_and_bad_arities() { + let model = sample_model(); + let error = |formula: &str| { + let expr = parse_expression(formula).expect("parses"); + Binder::new(&model).bind_expression(&expr).expect_err("should fail") + }; + assert!(error("Missing[Amount]").message.contains("unknown table")); + assert!(error("Sales[Missing]").message.contains("unknown column")); + // A measure qualifier has to name the measure's home table. + assert!(error("Date[Total Sales]").message.contains("belongs to table `Sales`")); + assert!(error("SUM ( )").message.contains("expects 1")); + assert!(error("NOPE ( 1 )").message.contains("unknown DAX function")); +} + +#[test] +fn binds_var_return_with_sequential_scopes() { + let model = sample_model(); + let bound = bind(&model, "VAR x = 1 VAR y = x + 1 RETURN y"); + match bound { + BoundExpr::VarReturn { vars, body } => { + assert_eq!(vars.len(), 2); + assert_eq!(vars[0].name, "x"); + assert_eq!(vars[1].name, "y"); + assert!(matches!(vars[0], BoundVariable { .. })); + assert!(matches!(*body, BoundExpr::Variable { index: 1, .. })); + } + other => panic!("expected VAR block, got {other:?}"), + } + + // A variable shadows a table of the same name. + assert!(matches!( + bind(&model, "VAR Sales = 1 RETURN Sales"), + BoundExpr::VarReturn { body, .. } if matches!(*body, BoundExpr::Variable { .. }) + )); +} + +#[test] +fn bracketed_names_bind_measures_before_variables() { + let mut model = DataModel { + tables: vec![ModelTable { + name: "Sales".into(), + columns: vec![ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }], + rows: vec![], + }], + relationships: vec![], + measures: vec![Measure { + name: "Total".into(), + formula: "SUM ( Sales[Amount] )".into(), + table: Some("Sales".into()), + format: None, + expr: None, + }], + }; + model.parse_formulas().expect("model parses"); + + // `[Total]` is a bracketed model reference, so it binds to the measure even though a + // variable of the same name is in scope. + match bind(&model, "VAR Total = 1 RETURN [Total]") { + BoundExpr::VarReturn { vars, body } => { + assert_eq!(vars.len(), 1); + assert_eq!(vars[0].name, "Total"); + assert!(matches!(*body, BoundExpr::Measure(0)), "expected measure, got {body:?}"); + } + other => panic!("expected VAR block, got {other:?}"), + } + + // A bare name still resolves to the variable. + assert!(matches!( + bind(&model, "VAR Total = 1 RETURN Total"), + BoundExpr::VarReturn { body, .. } if matches!(*body, BoundExpr::Variable { index: 0, .. }) + )); +} + +#[test] +fn pathitem_type_names_bind_as_keywords() { + let model = sample_model(); + for (formula, function, expected) in + [("PATHITEM ( \"1|2\", 1, TEXT )", "PATHITEM", "TEXT"), ("PATHITEMREVERSE ( \"1|2\", 1, INTEGER )", "PATHITEMREVERSE", "INTEGER")] + { + match bind(&model, formula) { + BoundExpr::Call { spec, args } => { + assert_eq!(spec.name, function); + assert_eq!(args.len(), 3); + assert!(matches!(&args[2], BoundExpr::Keyword(keyword) if keyword == expected), "expected `{expected}` keyword, got {:?}", args[2]); + } + other => panic!("expected call, got {other:?}"), + } + } +} + +#[test] +fn measures_and_dependencies_are_bound() { + let model = sample_model(); + let binder = Binder::new(&model); + let total = binder.bind_measure("Total Sales").expect("measure binds"); + assert!(total.dependencies.is_empty()); + let east = binder.bind_measure("East Sales").expect("measure binds"); + assert_eq!(east.dependencies, ["Total Sales".to_string()].into_iter().collect()); + + let graph = binder.dependency_graph().expect_err("cycle is rejected"); + assert!(graph.message.contains("circular")); +} + +#[test] +fn model_validation_rejects_duplicates_and_missing_relationship_columns() { + let mut model = sample_model(); + model.tables.push(ModelTable { name: "sales".into(), columns: vec![], rows: vec![] }); + assert!(model.parse_formulas().expect_err("duplicate table").message.contains("duplicate")); + + let mut model = sample_model(); + model.relationships.push(Relationship { + from_table: "Sales".into(), + from_column: "Missing".into(), + to_table: "Date".into(), + to_column: "Date".into(), + bidirectional: false, + inactive: false, + }); + assert!(model.parse_formulas().expect_err("missing column").message.contains("missing column")); +} + +#[test] +fn model_json_deserializes_and_parses_measures() { + let json = r#"{ + "tables": [{"name":"Sales","columns":[{"name":"Amount","data_type":"Double"}]}], + "relationships": [], + "measures": [{"name":"Total","formula":"SUM(Sales[Amount])","table":"Sales"}] + }"#; + let mut model: DataModel = serde_json::from_str(json).expect("json loads"); + model.parse_formulas().expect("model parses"); + assert!(model.measures[0].expr.is_some()); +} diff --git a/crates/dax/tests/data_types.rs b/crates/dax/tests/data_types.rs new file mode 100644 index 000000000..2514132a0 --- /dev/null +++ b/crates/dax/tests/data_types.rs @@ -0,0 +1,569 @@ +//! 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; the catalog return type is Boolean even + // though arity validation rejects the call. + assert!(matches!(parse("TRUE(1)").kind, ExprKind::Call(_))); + assert_eq!(infer("TRUE(1)"), Ok(data(DataType::Boolean))); + assert_eq!(infer("FALSE(1)"), Ok(data(DataType::Boolean))); +} + +#[test] +fn blank_is_a_call_not_a_literal() { + match parse("BLANK()").kind { + ExprKind::Call(call) => { + assert_eq!(call.name.text, "BLANK"); + assert!(call.args.is_empty()); + } + other => panic!("BLANK() is a call: {other:?}"), + } + assert_eq!(infer("BLANK()"), Ok(InferredType::Blank)); + assert!(matches!(parse("BLANK").kind, ExprKind::Name(_))); + assert_eq!(infer("BLANK"), Ok(InferredType::Unknown)); +} + +#[test] +fn literal_operator_inference() { + for (src, expected) in [ + ("1 + 2", data(DataType::Integer)), + ("1 - 2", data(DataType::Integer)), + ("1 * 2", data(DataType::Integer)), + ("1 / 2", data(DataType::Decimal)), + ("1.0 + 2", data(DataType::Decimal)), + ("1 + 2.0", data(DataType::Decimal)), + ("2 ^ 3", data(DataType::Decimal)), + ("1 & 2", data(DataType::String)), + // Excel: 12&34 is "1234"; the observed result is evaluator output, the type is String. + ("12 & 34", data(DataType::String)), + ("1 = 2", data(DataType::Boolean)), + // Excel: "Report" = "REPORT" is TRUE (case-insensitive collation is evaluator work). + ("\"Report\" = \"REPORT\"", data(DataType::Boolean)), + ("1 <> 2", data(DataType::Boolean)), + ("1 < 2", data(DataType::Boolean)), + ("1 > 2", data(DataType::Boolean)), + ("1 <= 2", data(DataType::Boolean)), + ("1 >= 2", data(DataType::Boolean)), + ("1 == 1", data(DataType::Boolean)), + ("TRUE && FALSE", data(DataType::Boolean)), + ("TRUE || FALSE", data(DataType::Boolean)), + ("NOT TRUE", data(DataType::Boolean)), + ("1 IN { 1 }", data(DataType::Boolean)), + ("(1, \"a\") IN { (1, \"a\") }", data(DataType::Boolean)), + ("TRUE() + 1", data(DataType::Integer)), + ("-1", data(DataType::Integer)), + ("+1", data(DataType::Integer)), + ("-1.5", data(DataType::Decimal)), + ("-TRUE()", data(DataType::Integer)), + ("dt\"2023-05-19\" + 1", data(DataType::DateTime)), + ("1 + dt\"2023-05-19\"", data(DataType::DateTime)), + ("dt\"2023-05-19\" - 1", data(DataType::DateTime)), + ("dt\"2023-05-19\" - dt\"2023-05-20\"", data(DataType::DateTime)), + ("SUM(1, 2)", InferredType::Unknown), + ("VALUES(T[Col])", InferredType::Table), + ] { + assert_eq!(infer(src), Ok(expected), "{src}"); + } + + for src in ["[Amount]", "\"22\" + 22", "[Amount] + 1", "[Amount] - 1"] { + assert_eq!(infer(src), Ok(InferredType::Unknown), "{src}"); + } +} + +#[test] +fn blank_arithmetic_keeps_blank_polymorphic() { + for (src, expected) in [ + ("BLANK() + 5", data(DataType::Integer)), + ("5 + BLANK()", data(DataType::Integer)), + ("BLANK() + 2.5", data(DataType::Decimal)), + ("BLANK() + TRUE()", data(DataType::Integer)), + ("BLANK() + dt\"2023-05-19\"", data(DataType::DateTime)), + ("BLANK() + BLANK()", InferredType::Blank), + ("BLANK() - BLANK()", InferredType::Blank), + ("BLANK() * 5", InferredType::Blank), + ("5 * BLANK()", InferredType::Blank), + ("BLANK() * BLANK()", InferredType::Blank), + ("5 / BLANK()", data(DataType::Decimal)), + ("0 / BLANK()", data(DataType::Decimal)), + ("BLANK() / 5", InferredType::Blank), + ("BLANK() / BLANK()", InferredType::Blank), + ("-BLANK()", InferredType::Blank), + ] { + assert_eq!(infer(src), Ok(expected), "{src}"); + } + + assert_eq!(infer("BLANK() + [Amount]"), Ok(InferredType::Unknown)); + assert_eq!(infer("BLANK() * [Amount]"), Ok(InferredType::Blank)); +} + +#[test] +fn incompatible_comparisons_and_coercions() { + for src in ["TRUE() = 1", "1 = TRUE()", "\"1\" = 1", "1 = \"1\"", "\"1\" > 0", "TRUE() == 1", "\"1\" == 1"] { + let error = match infer(src) { + Ok(inferred) => panic!("{src:?} unexpectedly inferred {inferred:?}"), + Err(error) => error, + }; + assert!(matches!(error, TypeError::IncompatibleOperands { .. }), "{src}: {error:?}"); + assert!(error.to_string().contains("cannot combine"), "{error}"); + } + + // BLANK is coerced to 0, "" or FALSE for `=`, and comparisons still yield Boolean. + for src in ["BLANK() = 0", "BLANK() <> 0", "BLANK() = \"\"", "BLANK() = FALSE()", "BLANK() = BLANK()"] { + assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}"); + } + + // `==` is strict and does not coerce BLANK, but the comparison is still well-typed. + for src in ["BLANK() == 0", "BLANK() == \"\"", "0 == BLANK()"] { + assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}"); + } + + assert_eq!(comparison_coercion(InferredType::Blank, data(DataType::Integer)), Ok(data(DataType::Integer))); + assert_eq!(comparison_coercion(InferredType::Blank, data(DataType::String)), Ok(data(DataType::String))); + assert_eq!(comparison_coercion(data(DataType::Boolean), InferredType::Blank), Ok(data(DataType::Boolean))); + assert_eq!(comparison_coercion(InferredType::Blank, InferredType::Blank), Ok(InferredType::Blank)); + assert_eq!(comparison_coercion(data(DataType::Integer), data(DataType::Currency)), Ok(data(DataType::Currency))); + assert_eq!( + comparison_coercion(data(DataType::String), data(DataType::Integer)), + Err(TypeError::IncompatibleTypes { left: data(DataType::String), right: data(DataType::Integer) }) + ); + assert_eq!( + comparison_coercion(data(DataType::Boolean), data(DataType::Integer)), + Err(TypeError::IncompatibleTypes { left: data(DataType::Boolean), right: data(DataType::Integer) }) + ); + assert_eq!( + comparison_coercion(InferredType::Table, InferredType::Blank), + Err(TypeError::IncompatibleTypes { left: InferredType::Table, right: InferredType::Blank }) + ); + + assert_eq!(comparison_compatible(BinaryOp::StrictEq, InferredType::Blank, data(DataType::Integer)), Ok(())); + assert_eq!( + comparison_compatible(BinaryOp::Eq, data(DataType::String), data(DataType::Integer)), + Err(TypeError::IncompatibleOperands { op: BinaryOp::Eq, left: data(DataType::String), right: data(DataType::Integer) }) + ); + assert_eq!( + comparison_compatible(BinaryOp::Eq, InferredType::Table, data(DataType::Integer)), + Err(TypeError::IncompatibleOperands { op: BinaryOp::Eq, left: InferredType::Table, right: data(DataType::Integer) }) + ); + assert_eq!(comparison_type(BinaryOp::Eq, data(DataType::Integer), data(DataType::Decimal)), Ok(DataType::Boolean)); +} + +#[test] +fn documented_arithmetic_result_matrices() { + use DataType::{Currency, DateTime, Decimal, Integer}; + + assert_eq!(numeric_matrix_order(), [Integer, Currency, Decimal, DateTime], "matrix order is Integer, Currency, Real, DateTime"); + + for (op, left, right, expected) in [ + // Addition: DateTime wins; Currency promotes against Integer and Decimal. + (BinaryOp::Add, Integer, Integer, Integer), + (BinaryOp::Add, Integer, Currency, Currency), + (BinaryOp::Add, Currency, Decimal, Decimal), + (BinaryOp::Add, Integer, DateTime, DateTime), + (BinaryOp::Add, DateTime, Integer, DateTime), + (BinaryOp::Add, DateTime, DateTime, DateTime), + // Subtraction: two dates are documented as DateTime. + (BinaryOp::Sub, Integer, Integer, Integer), + (BinaryOp::Sub, Integer, Currency, Currency), + (BinaryOp::Sub, Integer, DateTime, Decimal), + (BinaryOp::Sub, DateTime, Integer, DateTime), + (BinaryOp::Sub, DateTime, DateTime, DateTime), + // Multiplication reproduces the quirky published cells, including INT*DT -> INT. + (BinaryOp::Mul, Integer, Integer, Integer), + (BinaryOp::Mul, Integer, Currency, Currency), + (BinaryOp::Mul, Currency, Currency, Decimal), + (BinaryOp::Mul, Integer, DateTime, Integer), + (BinaryOp::Mul, Currency, DateTime, Currency), + (BinaryOp::Mul, Decimal, DateTime, Decimal), + // Division is Decimal for Integer/Integer and keeps the published Currency cells. + (BinaryOp::Div, Integer, Integer, Decimal), + (BinaryOp::Div, Integer, Currency, Currency), + (BinaryOp::Div, Currency, Currency, Decimal), + (BinaryOp::Div, Currency, Integer, Currency), + (BinaryOp::Div, DateTime, DateTime, Decimal), + (BinaryOp::Div, DateTime, Currency, Decimal), + ] { + assert_eq!(arithmetic(op, left, right), Ok(data(expected)), "{op:?} {left:?} {right:?}"); + } + + // The multiplication table has no DateTime row; DateTime on the left is a type error. + assert!(arithmetic(BinaryOp::Mul, DateTime, Integer).is_err()); + assert!(arithmetic(BinaryOp::Mul, DateTime, DateTime).is_err()); +} + +#[test] +fn documented_comparison_matrix_and_date_comparisons() { + use DataType::{Currency, DateTime, Decimal, Integer}; + + for (left, right, expected) in [ + (Integer, Integer, Integer), + (Integer, Currency, Currency), + (Currency, Currency, Currency), + (Integer, Decimal, Decimal), + (Integer, DateTime, Decimal), + (Currency, DateTime, Decimal), + (DateTime, DateTime, DateTime), + ] { + assert_eq!(comparison_coercion(data(left), data(right)), Ok(data(expected)), "{left:?} vs {right:?}"); + } + + for op in [BinaryOp::Eq, BinaryOp::Ne, BinaryOp::Lt, BinaryOp::Gt, BinaryOp::Le, BinaryOp::Ge, BinaryOp::StrictEq] { + assert_eq!(comparison_type(op, data(DateTime), data(DateTime)), Ok(DataType::Boolean), "date vs date with {op:?}"); + assert_eq!(comparison_type(op, data(DateTime), data(Integer)), Ok(DataType::Boolean), "date vs number with {op:?}"); + } + + assert_eq!(infer("dt\"2023-05-19\" = dt\"2023-05-20\""), Ok(data(DataType::Boolean))); + assert_eq!(infer("dt\"2023-05-19\" < 1"), Ok(data(DataType::Boolean))); +} + +#[test] +fn variant_and_binary_have_no_literals_or_operators() { + assert!(DataType::Variant.metadata().literal_syntax.is_none()); + assert!(DataType::Binary.metadata().literal_syntax.is_none()); + assert!(matches!(parse("VARIANT").kind, ExprKind::Name(_))); + // Container children still participate in inference. + assert!(infer("{ 1 + { 2 } }").is_err()); + assert!(infer("(1 + { 2 })").is_err()); + assert!(infer("SUM(1 + { 2 })").is_err()); + assert!(infer("VAR x = 1 + { 2 } RETURN 1").is_err()); + // Catalogued functions expose their documented return type; unknown names stay unknown. + assert_eq!(infer("SUM(Sales[Amount])"), Ok(InferredType::Unknown)); + assert_eq!(infer("NOT_A_DAX_FUNCTION(1)"), Ok(InferredType::Unknown)); + assert!(matches!(parse("BINARY").kind, ExprKind::Name(_))); + assert_eq!(infer("VARIANT"), Ok(InferredType::Unknown)); + assert_eq!(infer("BINARY"), Ok(InferredType::Unknown)); +} + +#[test] +fn unary_and_binary_type_helpers_reject_non_scalars() { + assert_eq!(unary_type(UnaryOp::Neg, data(DataType::Decimal)), Ok(data(DataType::Decimal))); + assert_eq!(unary_type(UnaryOp::Neg, data(DataType::DateTime)), Ok(data(DataType::DateTime))); + assert_eq!(unary_type(UnaryOp::Plus, data(DataType::Currency)), Ok(data(DataType::Currency))); + assert!(unary_type(UnaryOp::Neg, InferredType::Table).is_err()); + assert!(unary_type(UnaryOp::Neg, data(DataType::Binary)).is_err()); + assert_eq!( + unary_type(UnaryOp::Not, InferredType::Table), + Err(TypeError::IncompatibleUnaryOperand { op: UnaryOp::Not, operand: InferredType::Table }) + ); + + assert_eq!(binary_type(BinaryOp::Concat, data(DataType::Integer), data(DataType::Boolean)), Ok(data(DataType::String))); + assert_eq!(binary_type(BinaryOp::And, InferredType::Blank, data(DataType::Boolean)), Ok(data(DataType::Boolean))); + assert!(binary_type(BinaryOp::Concat, InferredType::Table, data(DataType::Integer)).is_err()); + assert!(binary_type(BinaryOp::In, data(DataType::Integer), data(DataType::Integer)).is_err()); + assert_eq!(binary_type(BinaryOp::In, data(DataType::Integer), InferredType::Table), Ok(data(DataType::Boolean))); + assert_eq!(binary_type(BinaryOp::Eq, data(DataType::Boolean), data(DataType::Boolean)), Ok(data(DataType::Boolean))); +} + +#[test] +fn table_calls_are_unknown_in_scalar_operand_positions() { + // A table-valued call may resolve to one row/column at evaluation time, so scalar operators + // accept it as unknown rather than rejecting a valid formula. + for src in ["LASTDATE('Date'[Date]) - 1", "FIRSTDATE('Date'[Order Date]) < TODAY()", "-VALUES(Sales[Amount])"] { + assert!(infer(src).is_ok(), "{src} should infer: {:?}", infer(src)); + } + assert_eq!(infer("LASTDATE('Date'[Date]) - 1"), Ok(InferredType::Unknown)); + // `IN` keeps its operands typed: the left must not be a table. + let error = infer("VALUES(Sales[Amount]) IN { 1 }").expect_err("a table on the left of IN"); + assert!(matches!(error, TypeError::IncompatibleOperands { .. }), "{error:?}"); +}