diff --git a/core/expression/src/compiler/compiler.rs b/core/expression/src/compiler/compiler.rs index 5643ddfa..0332c79c 100644 --- a/core/expression/src/compiler/compiler.rs +++ b/core/expression/src/compiler/compiler.rs @@ -423,7 +423,7 @@ impl<'arena, 'bytecode_ref> CompilerInner<'arena, 'bytecode_ref> { }), }, Node::FunctionCall { kind, arguments } => match kind { - FunctionKind::Internal(_) | FunctionKind::Deprecated(_) => { + FunctionKind::Internal(_) | FunctionKind::Deprecated(_) | FunctionKind::Host(_) => { let function = FunctionRegistry::get_definition(kind).ok_or_else(|| { CompilerError::UnknownFunction { name: kind.to_string(), @@ -554,6 +554,87 @@ impl<'arena, 'bytecode_ref> CompilerInner<'arena, 'bytecode_ref> { self.emit(Opcode::Array); Ok(self.emit(Opcode::Flatten)) } + ClosureFunction::Count if arguments.len() == 1 => { + self.compile_argument(kind, arguments, 0)?; + self.emit(Opcode::Begin); + self.emit(Opcode::GetLen); + Ok(self.emit(Opcode::End)) + } + ClosureFunction::Sum + | ClosureFunction::Avg + | ClosureFunction::Min + | ClosureFunction::Max + | ClosureFunction::Median + | ClosureFunction::Mode + | ClosureFunction::Stddev + | ClosureFunction::Variance + | ClosureFunction::TopK + | ClosureFunction::LastN + | ClosureFunction::Percentile + | ClosureFunction::CountDistinct + | ClosureFunction::Unique + | ClosureFunction::First + | ClosureFunction::Last => { + let (_, maximum) = c.callbacks(); + if arguments.len() > maximum + 1 { + return Err(CompilerError::InvalidFunctionCall { + name: kind.to_string(), + message: "Invalid number of arguments".to_string(), + }); + } + + // A parameter (`topK`'s count) sits between the + // projection and the filter. + let parameter = c.parameter(); + let filter_at = if parameter.is_some() { 3 } else { 2 }; + self.compile_argument(kind, arguments, 0)?; + self.emit(Opcode::Begin); + self.emit_loop(|c| { + let filtered = arguments.len() > filter_at; + let mut noop = 0; + if filtered { + c.compile_argument(kind, arguments, filter_at)?; + noop = c.emit(Opcode::Jump(Jump::IfFalse, 0)); + c.emit(Opcode::Pop); + } + + // The item (or its projection) joins the result + // unless it is null. + if arguments.len() > 1 { + c.compile_argument(kind, arguments, 1)?; + } else { + c.emit(Opcode::Pointer(0)); + } + let keep = c.emit(Opcode::Jump(Jump::IfNotNull, 0)); + c.emit(Opcode::Pop); + let skip = c.emit(Opcode::Jump(Jump::Forward, 0)); + let kept = c.bytecode.len(); + c.replace(keep, Opcode::Jump(Jump::IfNotNull, (kept - keep) as u32)); + c.emit(Opcode::IncrementCount); + let skipped = c.bytecode.len(); + c.replace(skip, Opcode::Jump(Jump::Forward, (skipped - skip) as u32)); + + if filtered { + let jmp = c.emit(Opcode::Jump(Jump::Forward, 0)); + c.replace(noop, Opcode::Jump(Jump::IfFalse, (jmp - noop) as u32)); + let e = c.emit(Opcode::Pop); + c.replace(jmp, Opcode::Jump(Jump::Forward, (e - jmp) as u32)); + } + Ok(()) + })?; + self.emit(Opcode::GetCount); + self.emit(Opcode::End); + self.emit(Opcode::Array); + let mut arg_count = 1; + if let Some(at) = parameter { + self.compile_argument(kind, arguments, at)?; + arg_count = 2; + } + Ok(self.emit(Opcode::CallFunction { + kind: kind.clone(), + arg_count, + })) + } ClosureFunction::Count => { self.compile_argument(kind, arguments, 0)?; self.emit(Opcode::Begin); diff --git a/core/expression/src/functions/internal.rs b/core/expression/src/functions/internal.rs index c9a02723..59ca18fc 100644 --- a/core/expression/src/functions/internal.rs +++ b/core/expression/src/functions/internal.rs @@ -34,6 +34,11 @@ pub enum InternalFunction { Rand, Median, Mode, + Stddev, + Variance, + Percentile, + TopK, + LastN, Floor, Ceil, Round, @@ -259,6 +264,40 @@ impl From<&InternalFunction> for Rc { signature: FunctionSignature::single(VT::Number.array(), VT::Number), }), + IF::Stddev => Rc::new(StaticFunction { + implementation: Rc::new(imp::stddev), + signature: FunctionSignature::single(VT::Number.array(), VT::Number), + }), + + IF::Variance => Rc::new(StaticFunction { + implementation: Rc::new(imp::variance), + signature: FunctionSignature::single(VT::Number.array(), VT::Number), + }), + + IF::Percentile => Rc::new(StaticFunction { + implementation: Rc::new(imp::percentile), + signature: FunctionSignature { + parameters: vec![VT::Number.array(), VT::Number], + return_type: VT::Number, + }, + }), + + IF::TopK => Rc::new(StaticFunction { + implementation: Rc::new(imp::top_k), + signature: FunctionSignature { + parameters: vec![VT::Any.array(), VT::Number], + return_type: VT::Any.array(), + }, + }), + + IF::LastN => Rc::new(StaticFunction { + implementation: Rc::new(imp::last_n), + signature: FunctionSignature { + parameters: vec![VT::Any.array(), VT::Number], + return_type: VT::Any.array(), + }, + }), + IF::Type => Rc::new(StaticFunction { implementation: Rc::new(imp::to_type), signature: FunctionSignature::single(VT::Any, VT::String), @@ -718,6 +757,140 @@ pub(crate) mod imp { Ok(V::Number(most_common)) } + /// Sample variance, exact in decimals: `(Σx² − (Σx)²/n) / (n − 1)`; + /// `None` below two values. Feature engines merging `(n, Σx, Σx²)` + /// across buckets use the same formula and get the same digits. + pub fn sample_variance(values: &[Decimal]) -> anyhow::Result> { + let mut sum = Decimal::ZERO; + let mut squares = Decimal::ZERO; + for x in values { + sum = sum.checked_add(*x).context("Number overflow")?; + squares = x + .checked_mul(*x) + .and_then(|sq| squares.checked_add(sq)) + .context("Number overflow")?; + } + variance_of(values.len() as i64, sum, squares) + } + + pub fn variance_of(n: i64, sum: Decimal, squares: Decimal) -> anyhow::Result> { + if n < 2 { + return Ok(None); + } + let n = Decimal::from(n); + let spread = sum + .checked_mul(sum) + .and_then(|s2| s2.checked_div(n)) + .and_then(|s2n| squares.checked_sub(s2n)) + .context("Number overflow")?; + let variance = spread + .checked_div(n - Decimal::ONE) + .context("Number overflow")?; + Ok(Some(variance.max(Decimal::ZERO).normalize())) + } + + pub fn sqrt_of(value: Decimal) -> anyhow::Result { + use rust_decimal::MathematicalOps; + Ok(value.sqrt().context("Square root of a negative number")?.normalize()) + } + + pub fn variance(args: Arguments) -> anyhow::Result { + let a = __internal_number_array(&args, 0)?; + Ok(sample_variance(&a)?.map_or(V::Null, V::Number)) + } + + pub fn stddev(args: Arguments) -> anyhow::Result { + let a = __internal_number_array(&args, 0)?; + match sample_variance(&a)? { + None => Ok(V::Null), + Some(variance) => Ok(V::Number(sqrt_of(variance)?)), + } + } + + /// Linear interpolation between the closest ranks of sorted values + /// (`q` in 0..=1): `x[⌊p⌋] + (p − ⌊p⌋)·(x[⌊p⌋+1] − x[⌊p⌋])`, `p = q·(n − 1)`. + pub fn percentile_of(sorted: &[Decimal], q: Decimal) -> anyhow::Result> { + if !(Decimal::ZERO..=Decimal::ONE).contains(&q) { + anyhow::bail!("Percentile must be between 0 and 1, got {q}"); + } + if sorted.is_empty() { + return Ok(None); + } + let position = q + .checked_mul(Decimal::from(sorted.len() - 1)) + .context("Number overflow")?; + let low = position.floor(); + let index = low.to_usize().context("Index out of bounds")?; + let fraction = position - low; + let value = if fraction.is_zero() { + sorted[index] + } else { + let (a, b) = (sorted[index], sorted[index + 1]); + b.checked_sub(a) + .and_then(|d| d.checked_mul(fraction)) + .and_then(|d| a.checked_add(d)) + .context("Number overflow")? + }; + Ok(Some(value.normalize())) + } + + fn __internal_count(args: &Arguments, pos: usize) -> anyhow::Result { + let n = args.number(pos)?; + if n.is_sign_negative() || !n.fract().is_zero() { + anyhow::bail!("Expected a whole number of items, got {n}"); + } + n.to_usize().context("Number of items is too large") + } + + /// The `k` most frequent non-null values (numbers or strings), most + /// frequent first; equal counts go to the smaller value. + pub fn top_k(args: Arguments) -> anyhow::Result { + let k = __internal_count(&args, 1)?; + let array = args.array(0)?; + let items = array.borrow(); + let mut numbers: BTreeMap = BTreeMap::new(); + let mut strings = BTreeMap::new(); + for item in items.iter() { + match item { + V::Null => {} + V::Number(n) => *numbers.entry(n.normalize()).or_insert(0) += 1, + V::String(s) => *strings.entry(s.clone()).or_insert(0) += 1, + _ => anyhow::bail!("Expected an array of numbers or strings"), + } + } + let mut ranked: Vec<(usize, V)> = numbers + .into_iter() + .map(|(n, c)| (c, V::Number(n))) + .chain(strings.into_iter().map(|(s, c)| (c, V::String(s)))) + .collect(); + // Stable: within a count, numbers then strings, each ascending. + ranked.sort_by(|a, b| b.0.cmp(&a.0)); + Ok(V::from_array(ranked.into_iter().take(k).map(|(_, v)| v).collect())) + } + + /// The last `n` non-null items, the last one first. + pub fn last_n(args: Arguments) -> anyhow::Result { + let n = __internal_count(&args, 1)?; + let array = args.array(0)?; + let items = array.borrow(); + Ok(V::from_array( + items + .iter() + .rev() + .filter(|item| !matches!(item, V::Null)) + .take(n) + .cloned() + .collect(), + )) + } + + pub fn percentile(args: Arguments) -> anyhow::Result { + let mut a = __internal_number_array(&args, 0)?; + let q = args.number(1)?; + a.sort(); + Ok(percentile_of(&a, q)?.map_or(V::Null, V::Number)) + } + pub fn to_type(args: Arguments) -> anyhow::Result { let a = args.var(0)?; Ok(V::String(a.type_name().into())) diff --git a/core/expression/src/functions/mod.rs b/core/expression/src/functions/mod.rs index c583821e..db10fbab 100644 --- a/core/expression/src/functions/mod.rs +++ b/core/expression/src/functions/mod.rs @@ -1,14 +1,18 @@ +pub use crate::functions::arguments::Arguments; pub use crate::functions::date_method::DateMethod; -pub use crate::functions::defs::FunctionTypecheck; +pub use crate::functions::defs::{ + CompositeFunction, FunctionDefinition, FunctionSignature, FunctionTypecheck, StaticFunction, +}; pub use crate::functions::deprecated::DeprecatedFunction; pub use crate::functions::internal::InternalFunction; pub use crate::functions::method::{MethodKind, MethodRegistry}; -pub use crate::functions::registry::FunctionRegistry; +pub use crate::functions::registry::{register_host_function, FunctionRegistry, HostFunction}; use std::fmt::Display; +use std::sync::Arc; use strum_macros::{Display, EnumIter, EnumString, IntoStaticStr}; -pub(crate) mod arguments; +pub mod arguments; mod date_method; pub(crate) mod defs; mod deprecated; @@ -21,6 +25,8 @@ pub enum FunctionKind { Internal(InternalFunction), Deprecated(DeprecatedFunction), Closure(ClosureFunction), + /// A function registered by the host application (see [`register_host_function`]). + Host(Arc), } impl TryFrom<&str> for FunctionKind { @@ -31,6 +37,10 @@ impl TryFrom<&str> for FunctionKind { .map(FunctionKind::Internal) .or_else(|_| DeprecatedFunction::try_from(value).map(FunctionKind::Deprecated)) .or_else(|_| ClosureFunction::try_from(value).map(FunctionKind::Closure)) + .or_else(|err| match registry::host_function_name(value) { + Some(name) => Ok(FunctionKind::Host(name)), + None => Err(err), + }) } } @@ -40,6 +50,7 @@ impl Display for FunctionKind { FunctionKind::Internal(i) => write!(f, "{i}"), FunctionKind::Deprecated(d) => write!(f, "{d}"), FunctionKind::Closure(c) => write!(f, "{c}"), + FunctionKind::Host(name) => write!(f, "{name}"), } } } @@ -55,4 +66,120 @@ pub enum ClosureFunction { Map, FlatMap, Count, + // Aggregates over the items, optionally projected and filtered: + // `sum(arr, #.amount, #.kind == 'in')`. Null projections are skipped. + Sum, + Avg, + Min, + Max, + Median, + Mode, + Stddev, + Variance, + // With a parameter after the projection, then the optional filter: + // `topK(items as t, t.merchant, 3 [, t.kind == 'in'])`. + TopK, + LastN, + Percentile, + CountDistinct, + Unique, + First, + Last, +} + +impl ClosureFunction { + /// Callbacks accepted after the array: `(required, maximum)`. + pub fn callbacks(&self) -> (usize, usize) { + match self { + ClosureFunction::All + | ClosureFunction::None + | ClosureFunction::Some + | ClosureFunction::One + | ClosureFunction::Filter + | ClosureFunction::Map + | ClosureFunction::FlatMap => (1, 1), + ClosureFunction::Count => (0, 1), + ClosureFunction::Sum + | ClosureFunction::Avg + | ClosureFunction::Min + | ClosureFunction::Max + | ClosureFunction::Median + | ClosureFunction::Mode + | ClosureFunction::Stddev + | ClosureFunction::Variance => (1, 2), + ClosureFunction::TopK | ClosureFunction::LastN | ClosureFunction::Percentile => { + (2, 3) + } + ClosureFunction::CountDistinct + | ClosureFunction::Unique + | ClosureFunction::First + | ClosureFunction::Last => (0, 2), + } + } + + /// Aggregates: the first callback projects an item, the second filters. + /// The others take one predicate (or mapping) callback. + pub fn is_aggregate(&self) -> bool { + !matches!( + self, + ClosureFunction::All + | ClosureFunction::None + | ClosureFunction::Some + | ClosureFunction::One + | ClosureFunction::Filter + | ClosureFunction::Map + | ClosureFunction::FlatMap + | ClosureFunction::Count + ) + } + + /// Whether callback `index` (1-based argument position) must return a bool. + pub fn is_predicate(&self, index: usize) -> bool { + match self { + ClosureFunction::Map | ClosureFunction::FlatMap => false, + c if c.parameter().is_some() => index == 3, + c if c.is_aggregate() => index == 2, + _ => index == 1, + } + } + + /// The argument position of a plain parameter (a count or fraction), + /// evaluated once rather than per item. + pub fn parameter(&self) -> Option { + matches!( + self, + ClosureFunction::TopK | ClosureFunction::LastN | ClosureFunction::Percentile + ) + .then_some(2) + } +} + +impl InternalFunction { + /// The callback form of an array aggregate: `sum([1, 2])` stays internal, + /// `sum(items, #.amount)` is [`ClosureFunction::Sum`]. + pub fn closure_form(&self) -> Option { + Some(match self { + InternalFunction::Sum => ClosureFunction::Sum, + InternalFunction::Avg => ClosureFunction::Avg, + InternalFunction::Min => ClosureFunction::Min, + InternalFunction::Max => ClosureFunction::Max, + InternalFunction::Median => ClosureFunction::Median, + InternalFunction::Mode => ClosureFunction::Mode, + InternalFunction::Stddev => ClosureFunction::Stddev, + InternalFunction::Variance => ClosureFunction::Variance, + _ => return None, + }) + } + + /// The callback form of a built-in that already takes a second argument + /// (`topK(arr, 3)`): used only with `as` or with three or more + /// arguments, so every two-argument call stays the built-in. + pub fn parameterized_closure_form(&self) -> Option { + Some(match self { + InternalFunction::TopK => ClosureFunction::TopK, + InternalFunction::LastN => ClosureFunction::LastN, + InternalFunction::Percentile => ClosureFunction::Percentile, + _ => return None, + }) + } } diff --git a/core/expression/src/functions/registry.rs b/core/expression/src/functions/registry.rs index a17c3645..dadbb837 100644 --- a/core/expression/src/functions/registry.rs +++ b/core/expression/src/functions/registry.rs @@ -1,9 +1,10 @@ -use crate::functions::defs::FunctionDefinition; -use crate::functions::{DeprecatedFunction, FunctionKind, InternalFunction}; +use crate::functions::defs::{FunctionDefinition, FunctionSignature, StaticFunction}; +use crate::functions::{ClosureFunction, DeprecatedFunction, FunctionKind, InternalFunction}; use nohash_hasher::{BuildNoHashHasher, IsEnabled}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; +use std::sync::{Arc, OnceLock, RwLock}; use strum::IntoEnumIterator; impl IsEnabled for InternalFunction {} @@ -17,6 +18,8 @@ pub struct FunctionRegistry { Rc, BuildNoHashHasher, >, + closure_aggregates: HashMap>, + host_functions: HashMap, Rc>, } impl FunctionRegistry { @@ -32,10 +35,47 @@ impl FunctionRegistry { FunctionKind::Deprecated(deprecated) => { Self::INSTANCE.with_borrow(|i| i.deprecated_functions.get(&deprecated).cloned()) } - FunctionKind::Closure(_) => None, + FunctionKind::Closure(closure) => { + Self::INSTANCE.with_borrow(|i| i.closure_aggregates.get(closure).cloned()) + } + FunctionKind::Host(name) => { + if let Some(found) = + Self::INSTANCE.with_borrow(|i| i.host_functions.get(name).cloned()) + { + return Some(found); + } + + let host = host_registry().read().ok()?.get(name).cloned()?; + let definition = (host.definition)(); + Self::INSTANCE + .with_borrow_mut(|i| i.host_functions.insert(name.clone(), definition.clone())); + Some(definition) + } } } + /// The registered host functions: name and description, sorted by name. + pub fn host_functions() -> Vec<(Arc, String)> { + let Ok(registry) = host_registry().read() else { + return Vec::new(); + }; + + let mut list: Vec<(Arc, String)> = registry + .iter() + .map(|(name, host)| (name.clone(), host.description.clone())) + .collect(); + list.sort(); + list + } + + pub(crate) fn host_description(name: &str) -> Option { + host_registry() + .read() + .ok()? + .get(name) + .map(|host| host.description.clone()) + } + fn new_internal() -> Self { let internal_functions = InternalFunction::iter() .map(|i| (i.clone(), (&i).into())) @@ -45,9 +85,206 @@ impl FunctionRegistry { .map(|i| (i.clone(), (&i).into())) .collect(); + let closure_aggregates = ClosureFunction::iter() + .filter(|c| c.is_aggregate()) + .map(|c| (c, aggregate::definition(c))) + .collect(); + Self { internal_functions, deprecated_functions, + closure_aggregates, + host_functions: HashMap::new(), } } } + +/// A function the host application adds to the language: the parser, the +/// type checker, intellisense and the VM accept it like a built-in. +/// +/// `definition` builds its [`FunctionDefinition`] (signatures, and the +/// implementation the VM calls); it runs once per thread that uses it. A +/// host that only parses and type-checks (and evaluates elsewhere) can give +/// an implementation that returns an error. +#[derive(Clone)] +pub struct HostFunction { + pub name: Arc, + pub description: String, + pub definition: Arc Rc + Send + Sync>, +} + +fn host_registry() -> &'static RwLock, HostFunction>> { + static REGISTRY: OnceLock, HostFunction>>> = OnceLock::new(); + REGISTRY.get_or_init(Default::default) +} + +/// Registers a host function for the whole process. Built-in names cannot +/// be taken; registering a name again replaces it on threads that have not +/// used it yet. +pub fn register_host_function(function: HostFunction) -> anyhow::Result<()> { + let name = function.name.as_ref(); + if InternalFunction::try_from(name).is_ok() + || DeprecatedFunction::try_from(name).is_ok() + || ClosureFunction::try_from(name).is_ok() + { + anyhow::bail!("`{name}` is a built-in function"); + } + + let mut registry = host_registry() + .write() + .map_err(|_| anyhow::anyhow!("host function registry is poisoned"))?; + registry.insert(function.name.clone(), function); + Ok(()) +} + +pub(crate) fn host_function_name(name: &str) -> Option> { + let registry = host_registry().read().ok()?; + registry.get_key_value(name).map(|(key, _)| key.clone()) +} + +/// What the callback forms of the aggregates do with the values they +/// collected (projected, filtered, nulls skipped). Empty input: `sum` and +/// `countDistinct` are `0`, `unique` is `[]`, the others are `null`. +mod aggregate { + use super::*; + use crate::functions::arguments::Arguments; + use crate::functions::internal::imp; + use crate::variable::VariableType as VT; + use crate::Variable; + use std::collections::HashSet; + + type Implementation = fn(Arguments) -> anyhow::Result; + + pub(super) fn definition(kind: ClosureFunction) -> Rc { + let (return_type, implementation): (VT, Implementation) = match kind { + ClosureFunction::Sum => (VT::Number, imp::sum), + ClosureFunction::Avg => (VT::Number, avg), + ClosureFunction::Min => (VT::Any, min), + ClosureFunction::Max => (VT::Any, max), + ClosureFunction::Median => (VT::Number, median), + ClosureFunction::Mode => (VT::Any, mode), + ClosureFunction::Stddev => (VT::Number, imp::stddev), + ClosureFunction::Variance => (VT::Number, imp::variance), + ClosureFunction::TopK | ClosureFunction::LastN | ClosureFunction::Percentile => { + let (return_type, implementation): (VT, Implementation) = match kind { + ClosureFunction::TopK => (VT::Any.array(), imp::top_k), + ClosureFunction::LastN => (VT::Any.array(), imp::last_n), + _ => (VT::Number, imp::percentile), + }; + return Rc::new(StaticFunction { + signature: FunctionSignature { + parameters: vec![VT::Any.array(), VT::Number], + return_type, + }, + implementation: Rc::new(implementation), + }); + } + ClosureFunction::CountDistinct => (VT::Number, count_distinct), + ClosureFunction::Unique => (VT::Any.array(), unique), + ClosureFunction::First => (VT::Any, first), + ClosureFunction::Last => (VT::Any, last), + _ => (VT::Any, unsupported), + }; + + Rc::new(StaticFunction { + signature: FunctionSignature::single(VT::Any.array(), return_type), + implementation: Rc::new(implementation), + }) + } + + fn null_if_empty(args: Arguments, f: Implementation) -> anyhow::Result { + if args.array(0)?.borrow().is_empty() { + return Ok(Variable::Null); + } + + f(args) + } + + fn avg(args: Arguments) -> anyhow::Result { + null_if_empty(args, imp::avg) + } + + fn min(args: Arguments) -> anyhow::Result { + null_if_empty(args, imp::min) + } + + fn max(args: Arguments) -> anyhow::Result { + null_if_empty(args, imp::max) + } + + fn median(args: Arguments) -> anyhow::Result { + null_if_empty(args, imp::median) + } + + /// The most common value (numbers or strings); ties go to the largest. + fn mode(args: Arguments) -> anyhow::Result { + let array = args.array(0)?; + let items = array.borrow(); + if items.is_empty() { + return Ok(Variable::Null); + } + if items.iter().all(|item| matches!(item, Variable::Number(_))) { + drop(items); + return imp::mode(args); + } + let mut counts = std::collections::BTreeMap::new(); + for item in items.iter() { + let Variable::String(s) = item else { + anyhow::bail!("Expected an array of numbers or strings"); + }; + *counts.entry(s.clone()).or_insert(0usize) += 1; + } + Ok(counts + .into_iter() + .max_by_key(|&(_, count)| count) + .map_or(Variable::Null, |(s, _)| Variable::String(s))) + } + + fn key(value: &Variable) -> String { + match value { + Variable::Number(n) => format!("number:{}", n.normalize()), + other => format!("{}:{other}", other.type_name()), + } + } + + fn distinct(args: &Arguments) -> anyhow::Result> { + let array = args.array(0)?; + let items = array.borrow(); + let mut seen = HashSet::with_capacity(items.len()); + Ok(items + .iter() + .filter(|item| !matches!(item, Variable::Null) && seen.insert(key(item))) + .cloned() + .collect()) + } + + fn count_distinct(args: Arguments) -> anyhow::Result { + Ok(Variable::Number(distinct(&args)?.len().into())) + } + + fn unique(args: Arguments) -> anyhow::Result { + Ok(Variable::from_array(distinct(&args)?)) + } + + fn first(args: Arguments) -> anyhow::Result { + Ok(args + .array(0)? + .borrow() + .first() + .cloned() + .unwrap_or(Variable::Null)) + } + + fn last(args: Arguments) -> anyhow::Result { + Ok(args + .array(0)? + .borrow() + .last() + .cloned() + .unwrap_or(Variable::Null)) + } + + fn unsupported(_: Arguments) -> anyhow::Result { + anyhow::bail!("not an aggregate") + } +} diff --git a/core/expression/src/intellisense/completion.rs b/core/expression/src/intellisense/completion.rs index c0d88f73..3a17f8ac 100644 --- a/core/expression/src/intellisense/completion.rs +++ b/core/expression/src/intellisense/completion.rs @@ -213,10 +213,18 @@ impl Completions { follow: None, }); + // The callback forms of `sum`, `avg`, ... share the built-in's name: + // one completion each, described with its callback form. completions.extend( InternalFunction::iter() + .filter(|f| f.closure_form().is_none()) .map(FunctionKind::Internal) .chain(ClosureFunction::iter().map(FunctionKind::Closure)) + .chain( + FunctionRegistry::host_functions() + .into_iter() + .map(|(name, _)| FunctionKind::Host(name)), + ) .map(|fk| Self::function(fk, None)), ); @@ -247,7 +255,7 @@ impl Completions { let detail = function_signature(&fk); let boost = boost_override.or(match &fk { FunctionKind::Internal(_) => Some(10), - FunctionKind::Closure(_) => None, + FunctionKind::Closure(_) | FunctionKind::Host(_) => None, FunctionKind::Deprecated(_) => Some(-20), }); @@ -352,6 +360,13 @@ fn function_info(fk: &FunctionKind) -> String { "Calculates the median value of all elements in the input array" } InternalFunction::Mode => "Finds the mode(s) of the input array", + InternalFunction::Stddev => "Sample standard deviation of the input array", + InternalFunction::Variance => "Sample variance of the input array", + InternalFunction::Percentile => { + "Value at a percentile (0 to 1) of the input array, interpolated" + } + InternalFunction::TopK => "The k most frequent values, most frequent first", + InternalFunction::LastN => "The last n values, the last one first", InternalFunction::Floor => "Rounds a number down to the nearest integer", InternalFunction::Ceil => "Rounds a number up to the nearest integer", InternalFunction::Round => "Rounds a number to a specified number of decimal places", @@ -411,8 +426,30 @@ fn function_info(fk: &FunctionKind) -> String { } ClosureFunction::Map => "Creates a new array by transforming each element", ClosureFunction::FlatMap => "Maps each element then flattens the result", - ClosureFunction::Count => "Counts elements that satisfy the condition", + ClosureFunction::Count => "Counts elements, or those that satisfy the condition", + ClosureFunction::Sum => "Sums the numbers, or a projection of matching elements", + ClosureFunction::Avg => "Averages the numbers, or a projection of matching elements", + ClosureFunction::Min => "Smallest value, or of a projection of matching elements", + ClosureFunction::Max => "Largest value, or of a projection of matching elements", + ClosureFunction::Median => "Median, or of a projection of matching elements", + ClosureFunction::Mode => "Most common value, or of a projection of matching elements", + ClosureFunction::Stddev => { + "Sample standard deviation, or of a projection of matching elements" + } + ClosureFunction::Variance => "Sample variance, or of a projection of matching elements", + ClosureFunction::TopK => "The k most frequent values of a projection of matching elements", + ClosureFunction::LastN => "The last n values of a projection of matching elements, the last one first", + ClosureFunction::Percentile => { + "Value at a percentile (0 to 1) of a projection of matching elements" + } + ClosureFunction::CountDistinct => "Counts distinct non-null values", + ClosureFunction::Unique => "Distinct non-null values, in first-seen order", + ClosureFunction::First => "First non-null value (of a projection of matching elements)", + ClosureFunction::Last => "Last non-null value (of a projection of matching elements)", }, + FunctionKind::Host(name) => { + return FunctionRegistry::host_description(name).unwrap_or_default(); + } }; s.to_string() } @@ -439,7 +476,12 @@ fn function_param_names(fk: &FunctionKind) -> Vec<&'static str> { | InternalFunction::Min | InternalFunction::Max | InternalFunction::Median - | InternalFunction::Mode => vec!["arr"], + | InternalFunction::Mode + | InternalFunction::Stddev + | InternalFunction::Variance => vec!["arr"], + InternalFunction::Percentile => vec!["arr", "q"], + InternalFunction::TopK => vec!["arr", "k"], + InternalFunction::LastN => vec!["arr", "n"], InternalFunction::Rand => vec!["max"], InternalFunction::Round | InternalFunction::Trunc => vec!["num", "digits"], InternalFunction::IsNumeric @@ -466,13 +508,13 @@ fn function_param_names(fk: &FunctionKind) -> Vec<&'static str> { DeprecatedFunction::Duration => vec!["duration"], DeprecatedFunction::StartOf | DeprecatedFunction::EndOf => vec!["timestamp", "unit"], }, - FunctionKind::Closure(_) => vec![], + FunctionKind::Closure(_) | FunctionKind::Host(_) => vec![], } } fn function_signature(fk: &FunctionKind) -> String { match fk { - FunctionKind::Internal(_) | FunctionKind::Deprecated(_) => { + FunctionKind::Internal(_) | FunctionKind::Deprecated(_) | FunctionKind::Host(_) => { let param_names = function_param_names(fk); let Some(definition) = FunctionRegistry::get_definition(fk) else { return String::new(); @@ -512,7 +554,25 @@ fn function_signature(fk: &FunctionKind) -> String { "(array: T[], callback: Callback) -> U[]".to_string() } ClosureFunction::Count => { - "(array: T[], callback: Callback) -> number".to_string() + "(array: T[], callback?: Callback) -> number".to_string() + } + ClosureFunction::Sum + | ClosureFunction::Avg + | ClosureFunction::Median + | ClosureFunction::Stddev + | ClosureFunction::Variance => "(array: number[] | T[], projection?: Callback, filter?: Callback) -> number".to_string(), + ClosureFunction::Mode => "(array: U[] | T[], projection?: Callback, filter?: Callback) -> U".to_string(), + ClosureFunction::TopK | ClosureFunction::LastN => "(array: T[], projection: Callback, n: number, filter?: Callback) -> U[]".to_string(), + ClosureFunction::Percentile => "(array: T[], projection: Callback, q: number, filter?: Callback) -> number".to_string(), + ClosureFunction::Min | ClosureFunction::Max => "(array: U[] | T[], projection?: Callback, filter?: Callback) -> U".to_string(), + ClosureFunction::CountDistinct => { + "(array: T[], projection?: Callback, filter?: Callback) -> number".to_string() + } + ClosureFunction::Unique => { + "(array: T[], projection?: Callback, filter?: Callback) -> U[]".to_string() + } + ClosureFunction::First | ClosureFunction::Last => { + "(array: T[], projection?: Callback, filter?: Callback) -> U".to_string() } }, } diff --git a/core/expression/src/intellisense/dependency.rs b/core/expression/src/intellisense/dependency.rs index c23d938a..b75a2216 100644 --- a/core/expression/src/intellisense/dependency.rs +++ b/core/expression/src/intellisense/dependency.rs @@ -679,7 +679,6 @@ impl<'a> DependencyResolutionWalker<'a> { if let FunctionKind::Closure(_) = kind { if arguments.len() >= 2 { let collection_node = arguments[0]; - let closure_node = arguments[1]; let collection_info = self.extract_path_with_spans(collection_node); let collection_source = collection_info @@ -687,44 +686,49 @@ impl<'a> DependencyResolutionWalker<'a> { .map(|(p, _)| p.clone()) .or_else(|| Self::collection_source_path(collection_node)); - let (alias, inner_reads, inner_refs) = match closure_node { - Node::Closure { body, alias } => { - let mut inner_scope = scope.clone(); - inner_scope.locals.insert(Variable::dollar_key_rc()); - inner_scope.pointer_collection = collection_source - .as_ref() - .filter(|source| !scope.is_local(source)) - .map(|source| scope.expand_alias_root(source)); + // Every callback (an aggregate's projection and its + // filter) reads through the same items. + let mut alias_found: Option> = None; + let mut inner_reads = Vec::new(); + let mut inner_refs = Vec::new(); + for &closure_node in &arguments[1..] { + let Node::Closure { body, alias } = closure_node else { + self.resolve(closure_node, scope); + return; + }; - match (alias, collection_source.as_ref()) { - (Some(alias_name), Some(source)) => { - let expanded = scope.expand_alias_root(source); - if scope.is_local(&expanded) { - inner_scope - .unresolved_aliases - .insert(Rc::from(*alias_name)); - } else { - inner_scope - .aliases - .insert(Rc::from(*alias_name), expanded); - } - } - (Some(alias_name), None) => { + let mut inner_scope = scope.clone(); + inner_scope.locals.insert(Variable::dollar_key_rc()); + inner_scope.pointer_collection = collection_source + .as_ref() + .filter(|source| !scope.is_local(source)) + .map(|source| scope.expand_alias_root(source)); + + match (alias, collection_source.as_ref()) { + (Some(alias_name), Some(source)) => { + let expanded = scope.expand_alias_root(source); + if scope.is_local(&expanded) { inner_scope .unresolved_aliases .insert(Rc::from(*alias_name)); + } else { + inner_scope.aliases.insert(Rc::from(*alias_name), expanded); } - _ => {} } - let (reads, refs) = - Self::walk_inner(body, &mut inner_scope, self.metadata); - (alias.map(|a| Rc::from(a)), reads, refs) + (Some(alias_name), None) => { + inner_scope.unresolved_aliases.insert(Rc::from(*alias_name)); + } + _ => {} } - _ => { - self.resolve(closure_node, scope); - return; + let (reads, refs) = + Self::walk_inner(body, &mut inner_scope, self.metadata); + if alias_found.is_none() { + alias_found = alias.map(Rc::from); } - }; + inner_reads.extend(reads); + inner_refs.extend(refs); + } + let alias = alias_found; match collection_info { Some((collection, spans)) if !scope.is_local(&collection) => { diff --git a/core/expression/src/intellisense/type_provider.rs b/core/expression/src/intellisense/type_provider.rs index 72211601..6624b3fd 100644 --- a/core/expression/src/intellisense/type_provider.rs +++ b/core/expression/src/intellisense/type_provider.rs @@ -565,7 +565,7 @@ impl TypesProvider { let mut type_list: Vec = arguments .iter() .enumerate() - .map(|(i, n)| match is_closure_kind && i == 1 { + .map(|(i, n)| match is_closure_kind && i >= 1 { true => VariableType::Any, false => self.determine(n, scope.clone()).kind, }) @@ -577,26 +577,28 @@ impl TypesProvider { .unwrap_or_else(|| Rc::new(VariableType::Any)); let ptr_type_inner = ptr_type.deref().clone(); - let alias = match arguments[1] { - Node::Closure { alias, .. } => *alias, - _ => None, - }; + for i in 1..arguments.len() { + let alias = match arguments[i] { + Node::Closure { alias, .. } => *alias, + _ => None, + }; - let mut closure_scope = IntelliSenseScope { - pointer_data: ptr_type_inner.clone(), - current_data: scope.current_data.clone(), - root_data: scope.root_data.clone(), - aliases: scope.aliases.clone(), - }; + let mut closure_scope = IntelliSenseScope { + pointer_data: ptr_type_inner.clone(), + current_data: scope.current_data.clone(), + root_data: scope.root_data.clone(), + aliases: scope.aliases.clone(), + }; - if let Some(alias_name) = alias { - closure_scope - .aliases - .insert(Rc::from(alias_name), ptr_type_inner); + if let Some(alias_name) = alias { + closure_scope + .aliases + .insert(Rc::from(alias_name), ptr_type_inner.clone()); + } + + let new_type = self.determine(arguments[i], closure_scope); + type_list[i] = new_type.kind; } - - let new_type = self.determine(arguments[1], closure_scope); - type_list[1] = new_type.kind; } match kind { @@ -612,7 +614,9 @@ impl TypesProvider { FunctionKind::Internal(InternalFunction::Values) => { self.values_typecheck(&type_list, arguments) } - FunctionKind::Internal(_) | FunctionKind::Deprecated(_) => { + FunctionKind::Internal(_) + | FunctionKind::Deprecated(_) + | FunctionKind::Host(_) => { let Some(def) = FunctionRegistry::get_definition(kind) else { return V(VariableType::Any); }; @@ -644,26 +648,27 @@ impl TypesProvider { ); } - if matches!( - c, - ClosureFunction::All - | ClosureFunction::None - | ClosureFunction::Some - | ClosureFunction::One - | ClosureFunction::Filter - | ClosureFunction::Count - ) { - if !type_list[1].satisfies(&VariableType::Bool) { + for i in 1..arguments.len() { + if c.is_predicate(i) && !type_list[i].satisfies(&VariableType::Bool) { self.set_error( - arguments[1], + arguments[i], format!( "Callback must return a `bool`, but its return type is `{}`.", - type_list[1] + type_list[i] ), ); } } + // What an aggregate reads: the projection, else the items. + let value_type = || match type_list.get(1) { + Some(projection) => projection.clone(), + None => type_list[0] + .iterator() + .map(|t| t.deref().clone()) + .unwrap_or(VariableType::Any), + }; + match c { ClosureFunction::All => V(VariableType::Bool), ClosureFunction::Some => V(VariableType::Bool), @@ -682,6 +687,24 @@ impl TypesProvider { }; V(VariableType::Array(Rc::new(element))) } + ClosureFunction::Sum + | ClosureFunction::Avg + | ClosureFunction::Median + | ClosureFunction::Stddev + | ClosureFunction::Variance + | ClosureFunction::Percentile + | ClosureFunction::CountDistinct => V(VariableType::Number), + ClosureFunction::TopK | ClosureFunction::LastN => { + V(VariableType::Array(Rc::new(value_type()))) + } + ClosureFunction::Mode + | ClosureFunction::Min + | ClosureFunction::Max + | ClosureFunction::First + | ClosureFunction::Last => V(value_type()), + ClosureFunction::Unique => { + V(VariableType::Array(Rc::new(value_type()))) + } } } } diff --git a/core/expression/src/parser/parser.rs b/core/expression/src/parser/parser.rs index 7c4c8601..4cd25900 100644 --- a/core/expression/src/parser/parser.rs +++ b/core/expression/src/parser/parser.rs @@ -111,6 +111,33 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { self.current.get().map(|token| &token.kind) } + /// Arguments of the call whose `(` was just read: top-level commas up to + /// the matching `)`, plus one. Looks ahead without moving. + fn arguments_ahead(&self) -> usize { + let mut depth = 0usize; + let mut count = 1; + for token in &self.tokens[self.position.get().min(self.tokens.len())..] { + match token.kind { + TokenKind::Bracket( + Bracket::LeftParenthesis | Bracket::LeftSquareBracket | Bracket::LeftCurlyBracket, + ) => depth += 1, + TokenKind::Bracket( + Bracket::RightParenthesis + | Bracket::RightSquareBracket + | Bracket::RightCurlyBracket, + ) => { + if depth == 0 { + break; + } + depth -= 1; + } + TokenKind::Operator(Operator::Comma) if depth == 0 => count += 1, + _ => {} + } + } + count + } + fn token_start(&self) -> u32 { match self.current() { None => self.tokens.last().map(|t| t.span.1).unwrap_or_default(), @@ -731,11 +758,47 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { }; self.next(); + + // `sum([1, 2])` is the built-in; `sum(items, #.amount)` and + // `sum(items as t, t.amount)` are its callback form. + let mut function = function; + let mut first_argument = None; + let closes_at_once = + self.current_kind() == Some(&TokenKind::Bracket(Bracket::RightParenthesis)); + if let FunctionKind::Internal(internal) = &function { + if let Some(closure) = internal + .parameterized_closure_form() + .filter(|_| !closes_at_once) + { + let many = self.arguments_ahead() >= 3; + let argument = expression_parser(ParserContext::Global); + let aliased = self + .current() + .is_some_and(|t| t.kind == TokenKind::Literal && t.value == "as"); + if many || aliased { + function = FunctionKind::Closure(closure); + } + first_argument = Some(argument); + } else if let Some(closure) = internal.closure_form().filter(|_| !closes_at_once) { + let argument = expression_parser(ParserContext::Global); + let continues = self.current().is_some_and(|t| { + t.kind == TokenKind::Operator(Operator::Comma) + || (t.kind == TokenKind::Literal && t.value == "as") + }); + if continues { + function = FunctionKind::Closure(closure); + } + first_argument = Some(argument); + } + } + let function_node = match function { - FunctionKind::Closure(_) => { + FunctionKind::Closure(closure) => { let mut arguments = BumpVec::new_in(&self.bump); - arguments.push(expression_parser(ParserContext::Global)); + arguments.push( + first_argument.unwrap_or_else(|| expression_parser(ParserContext::Global)), + ); let alias: Option<&'arena str> = if self @@ -767,11 +830,21 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { None }; - if let Some(error) = self.expect(TokenKind::Operator(Operator::Comma)) { - arguments.push(error); - }; + let (required, maximum) = closure.callbacks(); + for index in 0..maximum { + let more = self.current_kind() == Some(&TokenKind::Operator(Operator::Comma)); + if !more && index >= required { + break; + } + + if let Some(error) = self.expect(TokenKind::Operator(Operator::Comma)) { + arguments.push(error); + break; + }; + + arguments.push(self.closure(&expression_parser, alias)); + } - arguments.push(self.closure(&expression_parser, alias)); if let Some(error) = self.expect(TokenKind::Bracket(Bracket::RightParenthesis)) { arguments.push(error); } @@ -783,12 +856,19 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { } _ => { let mut arguments = BumpVec::new_in(&self.bump); + let mut parsed_first = first_argument; loop { - if self.current_kind() == Some(&TokenKind::Bracket(Bracket::RightParenthesis)) { - break; - } + if let Some(argument) = parsed_first.take() { + arguments.push(argument); + } else { + if self.current_kind() + == Some(&TokenKind::Bracket(Bracket::RightParenthesis)) + { + break; + } - arguments.push(expression_parser(ParserContext::Global)); + arguments.push(expression_parser(ParserContext::Global)); + } if self.current_kind() != Some(&TokenKind::Operator(Operator::Comma)) { break; } diff --git a/core/expression/src/parser/unary.rs b/core/expression/src/parser/unary.rs index b1b7b642..348a077e 100644 --- a/core/expression/src/parser/unary.rs +++ b/core/expression/src/parser/unary.rs @@ -356,6 +356,11 @@ impl From<&Node<'_>> for UnaryNodeBehaviour { InternalFunction::Rand => CompareWithReference(Equal), InternalFunction::Median => CompareWithReference(Equal), InternalFunction::Mode => CompareWithReference(Equal), + InternalFunction::Stddev => CompareWithReference(Equal), + InternalFunction::Variance => CompareWithReference(Equal), + InternalFunction::Percentile => CompareWithReference(Equal), + InternalFunction::TopK => CompareWithReference(In), + InternalFunction::LastN => CompareWithReference(In), InternalFunction::Floor => CompareWithReference(Equal), InternalFunction::Ceil => CompareWithReference(Equal), InternalFunction::Round => CompareWithReference(Equal), @@ -404,7 +409,22 @@ impl From<&Node<'_>> for UnaryNodeBehaviour { ClosureFunction::Map => CompareWithReference(In), ClosureFunction::FlatMap => CompareWithReference(In), ClosureFunction::Count => CompareWithReference(Equal), + ClosureFunction::Unique => CompareWithReference(In), + ClosureFunction::TopK | ClosureFunction::LastN => CompareWithReference(In), + ClosureFunction::Sum + | ClosureFunction::Avg + | ClosureFunction::Min + | ClosureFunction::Max + | ClosureFunction::Median + | ClosureFunction::Mode + | ClosureFunction::Stddev + | ClosureFunction::Variance + | ClosureFunction::Percentile + | ClosureFunction::CountDistinct + | ClosureFunction::First + | ClosureFunction::Last => CompareWithReference(Equal), }, + FunctionKind::Host(_) => CompareWithReference(Equal), }, Node::MethodCall { kind, .. } => match kind { MethodKind::DateMethod(dm) => match dm { diff --git a/core/expression/src/slot/literals.rs b/core/expression/src/slot/literals.rs index 2676f6cd..90785d0b 100644 --- a/core/expression/src/slot/literals.rs +++ b/core/expression/src/slot/literals.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use chrono_tz::Tz; -use crate::functions::{ClosureFunction, DateMethod, FunctionKind, InternalFunction, MethodKind}; +use crate::functions::{DateMethod, FunctionKind, InternalFunction, MethodKind}; use crate::lexer::{ ArithmeticOperator, Bracket, ComparisonOperator, LogicalOperator, Operator, QuotationMark, Token, TokenKind, @@ -230,11 +230,12 @@ impl<'a> NodeTable<'a> { ) -> Vec> { match kind { FunctionKind::Closure(cf) => { - let body_expected = match cf { - ClosureFunction::Map | ClosureFunction::FlatMap => None, - _ => Some(VariableType::Bool), - }; - vec![Self::closure_membership(parsed, arguments), body_expected] + let mut expected = vec![Self::closure_membership(parsed, arguments)]; + expected.extend( + (1..arguments.len().max(2)) + .map(|i| cf.is_predicate(i).then_some(VariableType::Bool)), + ); + expected } FunctionKind::Internal(InternalFunction::Date) => vec![Some(VariableType::Date)], FunctionKind::Internal(InternalFunction::Bool) => { diff --git a/core/expression/tests/data/analysis/closures.toml b/core/expression/tests/data/analysis/closures.toml index ee4367e9..6135e71b 100644 --- a/core/expression/tests/data/analysis/closures.toml +++ b/core/expression/tests/data/analysis/closures.toml @@ -262,3 +262,77 @@ diagnostics = [{ source = "type_check", severity = "error" }] [test.strict] diagnostics = [{ source = "type_check", severity = "error" }] + +# ── Aggregates with callbacks: projection, then filter ──────────────────────── + +[[test]] +name = "sum with projection and filter" +expression = "sum(items, #.amount, #.kind == 'in')" +input = '{"items": [{"amount": 1, "kind": "in"}]}' + +[test.loose] +return_type = '"Number"' + +[test.strict] +return_type = '"Number"' + +[[test]] +name = "sum with alias" +expression = "sum(items as t, t.amount, t.kind == 'in')" +input = '{"items": [{"amount": 1, "kind": "in"}]}' +reads = [ + { type = "iteration", collection = ["items"], alias = "t", reads = [ + { type = "direct", path = ["t", "amount"] }, + { type = "direct", path = ["t", "kind"] }, + ] }, +] + +[test.loose] +return_type = '"Number"' + +[test.strict] +return_type = '"Number"' + +[[test]] +name = "count without callback" +expression = "count(items)" +input = '{"items": [1, 2, 3]}' + +[test.loose] +return_type = '"Number"' + +[test.strict] +return_type = '"Number"' + +[[test]] +name = "unique of a projection" +expression = "unique(items, #.country)" +input = '{"items": [{"country": "GB"}]}' + +[test.loose] +return_type = '{"Array":"String"}' + +[test.strict] +return_type = '{"Array":"String"}' + +[[test]] +name = "max keeps the projection type" +expression = "max(items, #.amount)" +input = '{"items": [{"amount": 1}]}' + +[test.loose] +return_type = '"Number"' + +[test.strict] +return_type = '"Number"' + +[[test]] +name = "countDistinct filter must be a bool" +expression = "countDistinct(items, #.country, #.amount)" +input = '{"items": [{"country": "GB", "amount": 1}]}' + +[test.loose] +diagnostics = [{ source = "type_check", severity = "error" }] + +[test.strict] +diagnostics = [{ source = "type_check", severity = "error" }] diff --git a/core/expression/tests/data/analysis/completions.toml b/core/expression/tests/data/analysis/completions.toml index 23128630..39120780 100644 --- a/core/expression/tests/data/analysis/completions.toml +++ b/core/expression/tests/data/analysis/completions.toml @@ -201,3 +201,17 @@ expression = "'hello" pos = 6 input = '{"price": 10, "qty": 5}' includes = ["price", "qty", "sum"] + +[[test]] +name = "feature aggregates complete" +expression = "co" +pos = 2 +input = '{"items": []}' +includes = ["count", "countDistinct"] + +[[test]] +name = "first and last complete" +expression = "f" +pos = 1 +input = '{"items": []}' +includes = ["first", "filter", "flatMap"] diff --git a/core/expression/tests/data/standard.csv b/core/expression/tests/data/standard.csv index 87e73e3d..6993e97c 100644 --- a/core/expression/tests/data/standard.csv +++ b/core/expression/tests/data/standard.csv @@ -655,3 +655,74 @@ map(items, #.value * 2);{"items": [{"value": 1}, {"value": 2}]};[2, 4] # Backwards compatibility - # still works map([1, 2, 3], # * 2);;[2, 4, 6] filter([1, 2, 3, 4], # > 2);;[3, 4] + +# Aggregates with callbacks: projection, then filter. Null projections are skipped. +count([1, 2, 3]);;3 +count(items);{"items": [{"v": 1}, {"v": 2}]};2 +count([]);;0 +sum([1, 2, 3]);;6 +sum(items, #.v);{"items": [{"v": 1}, {"v": 2.5}, {"v": null}]};3.5 +sum(items, #.v, #.k == 'in');{"items": [{"v": 1, "k": "in"}, {"v": 2, "k": "out"}, {"v": 4, "k": "in"}]};5 +sum(items as t, t.v, t.k == 'in');{"items": [{"v": 1, "k": "in"}, {"v": 2, "k": "out"}, {"v": 4, "k": "in"}]};5 +sum(items, #.v, #.v > 100);{"items": [{"v": 1}, {"v": 2}]};0 +sum(map(filter(items, #.k == 'in'), #.v));{"items": [{"v": 1, "k": "in"}, {"v": 2, "k": "out"}]};1 +avg(items, #.v);{"items": [{"v": 1}, {"v": 2}, {"v": null}]};1.5 +avg(items, #.v, #.v > 100);{"items": [{"v": 1}]};null +avg([2, 4]);;3 +min(items, #.v);{"items": [{"v": 3}, {"v": 1}, {"v": 2}]};1 +max(items as i, i.v, i.v < 3);{"items": [{"v": 3}, {"v": 1}, {"v": 2}]};2 +max(items, #.v, #.v > 100);{"items": [{"v": 1}]};null +median(items, #.v);{"items": [{"v": 1}, {"v": 5}, {"v": 2}]};2 +mode(items, #.v);{"items": [{"v": 1}, {"v": 2}, {"v": 2}]};2 +countDistinct(items, #.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}, {"c": null}]};2 +countDistinct(items, #.c, #.c != 'DE');{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "FR"}]};2 +countDistinct([1, 1.0, 2, null]);;2 +unique([3, 1, 3, 2, 1]);;[3, 1, 2] +unique(items, #.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}]};["GB", "DE"] +first([4, 5, 6]);;4 +first(items, #.c);{"items": [{"c": null}, {"c": "DE"}, {"c": "GB"}]};'DE' +first(items, #.c, #.c != 'DE');{"items": [{"c": "DE"}, {"c": "GB"}]};'GB' +last(items, #.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": null}]};'DE' +last([]);;null +count(items, #.v > 1) + sum(items, #.v);{"items": [{"v": 1}, {"v": 2}]};4 +mode(items, #.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}]};'GB' +mode(items, #.c);{"items": [{"c": "DE"}, {"c": "GB"}]};'GB' +variance([1, 3, 5]);;4 +variance([5]);;null +stddev([1, 3, 5]);;2 +stddev(items, #.v, #.k == 'in');{"items": [{"v": 1, "k": "in"}, {"v": 2, "k": "out"}, {"v": 9, "k": "in"}]};5.6568542494923801952067548968 +variance(items, #.v);{"items": [{"v": 1}, {"v": null}]};null +percentile([1, 2, 3, 4], 0.5);;2.5 +percentile([10, 20, 30, 40, 50], 0.9);;46 +percentile([7], 0.99);;7 +percentile([], 0.5);;null +percentile(map(filter(items, #.k == 'in'), #.v), 1);{"items": [{"v": 1, "k": "in"}, {"v": 9, "k": "out"}, {"v": 3, "k": "in"}]};3 +topK(['GB', 'DE', 'GB', 'FR', 'DE', 'GB'], 2);;["GB", "DE"] +topK([3, 1, 3, 2, 1], 5);;[1, 3, 2] +topK(map(filter(items, #.k == 'in'), #.c), 1);{"items": [{"c": "DE", "k": "in"}, {"c": "GB", "k": "out"}, {"c": "GB", "k": "out"}]};["DE"] +topK([], 3);;[] +lastN([1, 2, 3, 4], 2);;[4, 3] +lastN(map(items, #.v), 5);{"items": [{"v": 1}, {"v": null}, {"v": 3}]};[3, 1] +topK(items as t, t.c, 1);{"items": [{"c": "DE"}, {"c": "GB"}, {"c": "GB"}]};["GB"] +topK(items, #.c, 1);{"items": [{"c": "DE"}, {"c": "GB"}, {"c": "GB"}]};["GB"] +topK(items as t, t.c, 2, t.k == 'in');{"items": [{"c": "DE", "k": "in"}, {"c": "GB", "k": "out"}, {"c": "FR", "k": "in"}]};["DE", "FR"] +lastN(items as t, t.v, 2);{"items": [{"v": 1}, {"v": 2}, {"v": null}, {"v": 3}]};[3, 2] +lastN(items, #.v, 2, #.v > 1);{"items": [{"v": 1}, {"v": 2}, {"v": 3}]};[3, 2] +percentile(items as t, t.v, 0.5);{"items": [{"v": 1}, {"v": 2}, {"v": 3}, {"v": 4}]};2.5 +percentile(items, #.v, 1, #.v < 4);{"items": [{"v": 1}, {"v": 2}, {"v": 3}, {"v": 4}]};3 +percentile([1, 2, 3, 4], 0.5);;2.5 +topK(['a', 'b', 'b'], 1);;["b"] +lastN([1, 2, 3], 1);;[3] +count(items as t, t.v > 1);{"items": [{"v": 1}, {"v": 2}, {"v": 3}]};2 +all(items as t, t.v > 0);{"items": [{"v": 1}, {"v": 2}]};true +some(items as t, t.v > 1);{"items": [{"v": 1}, {"v": 2}]};true +none(items as t, t.v > 5);{"items": [{"v": 1}, {"v": 2}]};true +one(items as t, t.v > 1);{"items": [{"v": 1}, {"v": 2}]};true +map(filter(items as t, t.v > 1) as t, t.v * 10);{"items": [{"v": 1}, {"v": 2}]};[20] +flatMap(items as t, [t.v, t.v]);{"items": [{"v": 1}, {"v": 2}]};[1, 1, 2, 2] +median(items as t, t.v);{"items": [{"v": 1}, {"v": 5}, {"v": 2}]};2 +mode(items as t, t.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}]};'GB' +stddev(items as t, t.v, t.k == 'in');{"items": [{"v": 1, "k": "in"}, {"v": 2, "k": "out"}, {"v": 3, "k": "in"}, {"v": 5, "k": "in"}]};2 +countDistinct(items as t, t.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}]};2 +unique(items as t, t.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}]};["GB", "DE"] +first(items as t, t.c, t.c != 'GB');{"items": [{"c": "GB"}, {"c": "DE"}]};'DE' diff --git a/core/expression/tests/host.rs b/core/expression/tests/host.rs new file mode 100644 index 00000000..88f39722 --- /dev/null +++ b/core/expression/tests/host.rs @@ -0,0 +1,109 @@ +use rust_decimal::Decimal; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::functions::{ + register_host_function, Arguments, FunctionSignature, HostFunction, StaticFunction, +}; +use zen_expression::intellisense::IntelliSense; +use zen_expression::variable::{Variable, VariableType}; +use zen_expression::Isolate; + +fn register_double() { + register_host_function(HostFunction { + name: Arc::from("double"), + description: "Doubles a number".to_string(), + definition: Arc::new(|| { + Rc::new(StaticFunction { + signature: FunctionSignature::single(VariableType::Number, VariableType::Number), + implementation: Rc::new(|args: Arguments| { + Ok(Variable::Number(args.number(0)? * Decimal::from(2))) + }), + }) + }), + }) + .unwrap(); +} + +#[test] +fn host_functions_run_on_every_thread() { + register_double(); + + let mut isolate = Isolate::new(); + assert_eq!( + isolate.run_standard("double(21) + 1").unwrap(), + Variable::Number(Decimal::from(43)) + ); + + let other = std::thread::spawn(|| { + Isolate::new() + .run_standard("double(2)") + .unwrap() + .to_value() + }) + .join() + .unwrap(); + assert_eq!(other, serde_json::json!(4)); +} + +#[test] +fn host_functions_are_type_checked_and_completed() { + register_double(); + let mut intellisense = IntelliSense::new(); + + let analysis = intellisense.analyze("double(2)", &VariableType::Any); + assert!(analysis.diagnostics.is_empty(), "{:?}", analysis.diagnostics); + assert_eq!(analysis.return_type, VariableType::Number); + + let analysis = intellisense.analyze("double('x')", &VariableType::Any); + assert!(!analysis.diagnostics.is_empty()); + + let completions = intellisense.completions("dou", 3, &VariableType::Any); + let double = completions + .iter() + .find(|c| c.label == "double") + .expect("double completes"); + assert_eq!(double.info, "Doubles a number"); +} + +#[test] +fn built_in_names_cannot_be_taken_and_unknown_names_stay_unknown() { + let taken = register_host_function(HostFunction { + name: Arc::from("countDistinct"), + description: String::new(), + definition: Arc::new(|| { + Rc::new(StaticFunction { + signature: FunctionSignature::single(VariableType::Any, VariableType::Any), + implementation: Rc::new(|_: Arguments| Ok(Variable::Null)), + }) + }), + }); + assert!(taken.is_err()); + + assert!(Isolate::new().run_standard("notRegistered(1)").is_err()); +} + +#[test] +fn a_parse_only_host_function_fails_when_evaluated() { + register_host_function(HostFunction { + name: Arc::from("windowed"), + description: "Compiled by the host, never evaluated here".to_string(), + definition: Arc::new(|| { + Rc::new(StaticFunction { + signature: FunctionSignature::single(VariableType::Any, VariableType::Number), + implementation: Rc::new(|_: Arguments| { + anyhow::bail!("`windowed` is evaluated by the host") + }), + }) + }), + }) + .unwrap(); + + let analysis = IntelliSense::new().analyze("windowed(items) > 1", &VariableType::Any); + assert!(analysis.diagnostics.is_empty(), "{:?}", analysis.diagnostics); + + let err = Isolate::new() + .run_standard("windowed([1])") + .unwrap_err() + .to_string(); + assert!(err.contains("evaluated by the host"), "{err}"); +}