mirror of
https://github.com/gorules/zen.git
synced 2026-11-29 16:07:47 +00:00
feat(expression): host function registry, count_distinct alias, null-skipping mode and statistics
Ports register_host_function/HostFunction from 3def2637 onto the lane VM branch:
FunctionKind::Host is parsed, type-checked, completed, compiled by the stack VM and
driven by the lane VM through the registry definition. mode, stddev, variance,
percentile and percentileApprox over plain lists skip nulls like their callback forms.
This commit is contained in:
@@ -431,7 +431,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(),
|
||||
|
||||
@@ -422,6 +422,17 @@ pub(crate) mod imp {
|
||||
.context("Expected a number array")
|
||||
}
|
||||
|
||||
fn __internal_present_numbers(args: &Arguments, pos: usize) -> anyhow::Result<Vec<Decimal>> {
|
||||
let a = args.array(pos)?;
|
||||
let arr = a.borrow();
|
||||
|
||||
arr.iter()
|
||||
.filter(|v| !matches!(v, V::Null))
|
||||
.map(|v| v.as_number())
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.context("Expected a number array")
|
||||
}
|
||||
|
||||
enum Either<A, B> {
|
||||
Left(A),
|
||||
Right(B),
|
||||
@@ -805,7 +816,11 @@ pub(crate) mod imp {
|
||||
/// The most common value of numbers or strings; ties go to the largest.
|
||||
pub fn mode(args: Arguments) -> anyhow::Result<V> {
|
||||
let array = args.array(0)?;
|
||||
let items = array.borrow();
|
||||
let all = array.borrow();
|
||||
if !all.is_empty() && all.iter().all(|item| matches!(item, V::Null)) {
|
||||
return Ok(V::Null);
|
||||
}
|
||||
let items: Vec<&V> = all.iter().filter(|item| !matches!(item, V::Null)).collect();
|
||||
if items.iter().all(|item| matches!(item, V::Number(_))) {
|
||||
let mut counts = BTreeMap::new();
|
||||
for item in items.iter() {
|
||||
@@ -872,12 +887,12 @@ pub(crate) mod imp {
|
||||
}
|
||||
|
||||
pub fn variance(args: Arguments) -> anyhow::Result<V> {
|
||||
let a = __internal_number_array(&args, 0)?;
|
||||
let a = __internal_present_numbers(&args, 0)?;
|
||||
Ok(sample_variance(&a)?.map_or(V::Null, V::Number))
|
||||
}
|
||||
|
||||
pub fn stddev(args: Arguments) -> anyhow::Result<V> {
|
||||
let a = __internal_number_array(&args, 0)?;
|
||||
let a = __internal_present_numbers(&args, 0)?;
|
||||
match sample_variance(&a)? {
|
||||
None => Ok(V::Null),
|
||||
Some(variance) => Ok(V::Number(sqrt_of(variance)?)),
|
||||
@@ -962,7 +977,7 @@ pub(crate) mod imp {
|
||||
}
|
||||
|
||||
pub fn percentile(args: Arguments) -> anyhow::Result<V> {
|
||||
let mut a = __internal_number_array(&args, 0)?;
|
||||
let mut a = __internal_present_numbers(&args, 0)?;
|
||||
let q = args.number(1)?;
|
||||
a.sort();
|
||||
Ok(percentile_of(&a, q)?.map_or(V::Null, V::Number))
|
||||
@@ -971,7 +986,7 @@ pub(crate) mod imp {
|
||||
/// The DDSketch estimate (1% relative accuracy) of the value at a
|
||||
/// fraction `q` (0 to 1) of the numbers: no interpolation.
|
||||
pub fn percentile_approx(args: Arguments) -> anyhow::Result<V> {
|
||||
let values = __internal_number_array(&args, 0)?;
|
||||
let values = __internal_present_numbers(&args, 0)?;
|
||||
let q = args.number(1)?;
|
||||
if !(Decimal::ZERO..=Decimal::ONE).contains(&q) {
|
||||
anyhow::bail!("Percentile must be between 0 and 1, got {q}");
|
||||
|
||||
@@ -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;
|
||||
@@ -23,6 +27,7 @@ pub enum FunctionKind {
|
||||
Internal(InternalFunction),
|
||||
Deprecated(DeprecatedFunction),
|
||||
Closure(ClosureFunction),
|
||||
Host(Arc<str>),
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for FunctionKind {
|
||||
@@ -33,6 +38,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),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +51,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}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,6 +82,7 @@ pub enum ClosureFunction {
|
||||
TopK,
|
||||
LastN,
|
||||
Percentile,
|
||||
#[strum(to_string = "countDistinct", serialize = "count_distinct")]
|
||||
CountDistinct,
|
||||
Unique,
|
||||
/// Selectors return an item, or a projection of it.
|
||||
|
||||
@@ -4,6 +4,7 @@ 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 {}
|
||||
@@ -18,6 +19,7 @@ pub struct FunctionRegistry {
|
||||
BuildNoHashHasher<DeprecatedFunction>,
|
||||
>,
|
||||
closure_aggregates: HashMap<ClosureFunction, Rc<dyn FunctionDefinition>>,
|
||||
host_functions: HashMap<Arc<str>, Rc<dyn FunctionDefinition>>,
|
||||
}
|
||||
|
||||
impl FunctionRegistry {
|
||||
@@ -36,9 +38,43 @@ impl FunctionRegistry {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn host_functions() -> Vec<(Arc<str>, String)> {
|
||||
let Ok(registry) = host_registry().read() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut list: Vec<(Arc<str>, String)> = registry
|
||||
.iter()
|
||||
.map(|(name, host)| (name.clone(), host.description.clone()))
|
||||
.collect();
|
||||
list.sort();
|
||||
list
|
||||
}
|
||||
|
||||
pub(crate) fn host_description(name: &str) -> Option<String> {
|
||||
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()))
|
||||
@@ -56,10 +92,44 @@ impl FunctionRegistry {
|
||||
internal_functions,
|
||||
deprecated_functions,
|
||||
closure_aggregates,
|
||||
host_functions: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HostFunction {
|
||||
pub name: Arc<str>,
|
||||
pub description: String,
|
||||
pub definition: Arc<dyn Fn() -> Rc<dyn FunctionDefinition> + Send + Sync>,
|
||||
}
|
||||
|
||||
fn host_registry() -> &'static RwLock<HashMap<Arc<str>, HostFunction>> {
|
||||
static REGISTRY: OnceLock<RwLock<HashMap<Arc<str>, HostFunction>>> = OnceLock::new();
|
||||
REGISTRY.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
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<Arc<str>> {
|
||||
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`,
|
||||
/// `countDistinct` and `countDistinctApprox` are `0`, `unique` is `[]`,
|
||||
|
||||
@@ -225,6 +225,11 @@ impl Completions {
|
||||
.filter(|f| f.closure_form().is_none() && f.parameterized_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)),
|
||||
);
|
||||
|
||||
@@ -257,7 +262,7 @@ impl Completions {
|
||||
// Aggregates rank with the built-ins, most of which they extend.
|
||||
FunctionKind::Internal(_) => Some(10),
|
||||
FunctionKind::Closure(c) if c.is_aggregate() => Some(10),
|
||||
FunctionKind::Closure(_) => None,
|
||||
FunctionKind::Closure(_) | FunctionKind::Host(_) => None,
|
||||
FunctionKind::Deprecated(_) => Some(-20),
|
||||
});
|
||||
|
||||
@@ -329,6 +334,9 @@ impl Completions {
|
||||
|
||||
fn function_info(fk: &FunctionKind) -> String {
|
||||
let s = match fk {
|
||||
FunctionKind::Host(name) => {
|
||||
return FunctionRegistry::host_description(name).unwrap_or_default();
|
||||
}
|
||||
FunctionKind::Internal(i) => match i {
|
||||
InternalFunction::Len => "Returns the length of variable",
|
||||
InternalFunction::Contains => "Checks if variable contains a needle",
|
||||
@@ -467,6 +475,7 @@ fn function_info(fk: &FunctionKind) -> String {
|
||||
|
||||
fn function_param_names(fk: &FunctionKind) -> Vec<&'static str> {
|
||||
match fk {
|
||||
FunctionKind::Host(_) => vec![],
|
||||
FunctionKind::Internal(i) => match i {
|
||||
InternalFunction::Len => vec!["var"],
|
||||
InternalFunction::Contains => vec!["haystack", "needle"],
|
||||
@@ -526,7 +535,7 @@ fn function_param_names(fk: &FunctionKind) -> Vec<&'static str> {
|
||||
|
||||
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();
|
||||
|
||||
@@ -775,7 +775,7 @@ 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);
|
||||
};
|
||||
|
||||
@@ -41,6 +41,7 @@ impl Builtins {
|
||||
}
|
||||
// A callback aggregate's final step (the collected values in).
|
||||
FunctionKind::Closure(closure) => return Registered::aggregate(*closure),
|
||||
FunctionKind::Host(_) => return Some(&Registered::HOST),
|
||||
};
|
||||
Some(match function {
|
||||
F::Len => &Text::LEN,
|
||||
@@ -175,6 +176,9 @@ impl Builtins {
|
||||
hint: &mut usize,
|
||||
) -> Result<Out, Fault> {
|
||||
let failed = |message: Fail| CallFault::message(kind, message);
|
||||
if let FunctionKind::Host(_) = kind {
|
||||
return Registered::host(kind, args).map_err(failed);
|
||||
}
|
||||
if let Some(overload) = builtin.overloads.get(*hint) {
|
||||
if let Some(result) = overload(args) {
|
||||
return result.map_err(failed);
|
||||
@@ -201,7 +205,11 @@ impl Builtins {
|
||||
kind: &FunctionKind,
|
||||
args: &[Arg],
|
||||
) -> Result<Out, VMError> {
|
||||
Self::resolve(builtin, args).map_err(|message| {
|
||||
let result = match kind {
|
||||
FunctionKind::Host(_) => Registered::host(kind, args),
|
||||
_ => Self::resolve(builtin, args),
|
||||
};
|
||||
result.map_err(|message| {
|
||||
Ops::error(
|
||||
"CallFunction",
|
||||
format!("Function `{kind}` failed: {message}"),
|
||||
|
||||
@@ -82,6 +82,15 @@ registered! {
|
||||
}
|
||||
|
||||
impl Registered {
|
||||
pub(crate) const HOST: Builtin = Builtin {
|
||||
overloads: &[],
|
||||
fail: |_| String::from("host function called without its name"),
|
||||
};
|
||||
|
||||
pub(crate) fn host(kind: &FunctionKind, args: &[Arg]) -> Result<Out, String> {
|
||||
drive(kind, args).unwrap_or_else(|| Err(format!("Function `{kind}` not found")))
|
||||
}
|
||||
|
||||
/// The final step of a callback aggregate (`sum(items, #.v)` …): the
|
||||
/// collected values (and the parameter) in, the aggregate out. `None`
|
||||
/// for the callbacks that are no aggregate (`map`, `filter`, `count`…).
|
||||
|
||||
@@ -1585,7 +1585,7 @@ impl<'a> LaneCompiler<'a> {
|
||||
_ => false,
|
||||
},
|
||||
FunctionKind::Internal(_) => true,
|
||||
FunctionKind::Deprecated(_) | FunctionKind::Closure(_) => false,
|
||||
FunctionKind::Deprecated(_) | FunctionKind::Closure(_) | FunctionKind::Host(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2131,7 +2131,7 @@ impl<'a> LaneCompiler<'a> {
|
||||
operator,
|
||||
} => self.binary_node(left, *operator, right)?,
|
||||
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(),
|
||||
|
||||
@@ -1371,6 +1371,7 @@ impl<'h, 'a> KernelBuilder<'h, 'a> {
|
||||
let function = match kind {
|
||||
FunctionKind::Internal(function) => function,
|
||||
FunctionKind::Closure(closure) => return self.closure(*closure, arguments),
|
||||
FunctionKind::Host(_) => return None,
|
||||
FunctionKind::Deprecated(_) => {
|
||||
let builtin = Builtins::of(kind)?;
|
||||
let returns = FunctionRegistry::get_definition(kind)
|
||||
|
||||
@@ -432,6 +432,7 @@ impl From<&Node<'_>> for UnaryNodeBehaviour {
|
||||
| ClosureFunction::CountDistinctApprox
|
||||
| ClosureFunction::PercentileApprox => CompareWithReference(Equal),
|
||||
},
|
||||
FunctionKind::Host(_) => CompareWithReference(Equal),
|
||||
},
|
||||
Node::MethodCall { kind, .. } => match kind {
|
||||
MethodKind::DateMethod(dm) => match dm {
|
||||
|
||||
@@ -773,6 +773,26 @@ abs(percentileApprox(items, #.v, 0.5) - 50) / 50 <= 0.01;{"items": [{"v": 10}, {
|
||||
abs(percentileApprox(map([1..100], #), #, 0.9) - 90) / 90 <= 0.01;;true
|
||||
abs(percentileApprox(items as t, t.v, 1, t.v < 1000) - 999) / 999 <= 0.01;{"items": [{"v": 999}, {"v": 5000}, {"v": -3}]};true
|
||||
map(groups, percentileApprox(#.items as t, t.v, #.q));{"groups": [{"q": 0, "items": [{"v": 1}, {"v": 2}]}, {"q": 0.5, "items": [{"v": 0}]}]};[0.99, 0]
|
||||
count_distinct([1, 1.0, 2, null]);;2
|
||||
count_distinct(items, #.c);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}, {"c": null}]};2
|
||||
count_distinct(items as t, t.c, t.c != 'DE');{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "FR"}]};2
|
||||
mode([1, null, 1, 2]);;1
|
||||
mode(['a', null, 'b', 'b']);;'b'
|
||||
mode([null, null]);;null
|
||||
mode(items as t, t.c);{"items": [{"c": "GB"}, {"c": null}, {"c": null}, {"c": "DE"}, {"c": "GB"}]};'GB'
|
||||
mode(items, #.v, #.k == 'in');{"items": [{"v": 1, "k": "in"}, {"v": 2, "k": "out"}, {"v": 2, "k": "out"}, {"v": 1, "k": "in"}]};1
|
||||
first([null, 4, 5]);;4
|
||||
last([4, 5, null]);;5
|
||||
first([null, null]);;null
|
||||
last(items as t, t.c);{"items": [{"c": "DE"}, {"c": "GB"}, {"c": null}]};'GB'
|
||||
last(items, #.c, #.c != 'GB');{"items": [{"c": "DE"}, {"c": "GB"}]};'DE'
|
||||
stddev([1, null, 3, 5]);;2
|
||||
variance([1, null, 3, 5]);;4
|
||||
variance(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"}]};4
|
||||
percentile([null, 1, 2, 3], 0.5);;2
|
||||
percentile(items as t, t.v, 0.5, t.v > 1);{"items": [{"v": 1}, {"v": 2}, {"v": 4}]};3
|
||||
topK(items as t, t.c, 1);{"items": [{"c": "GB"}, {"c": "DE"}, {"c": "GB"}, {"c": null}]};['GB']
|
||||
lastN(items as t, t.v, 2, t.v != 3);{"items": [{"v": 1}, {"v": 2}, {"v": 3}]};[2, 1]
|
||||
|
||||
# join: the inverse of split; separator defaults to ','; null items skipped
|
||||
join(['a', 'b', 'c'], ', ');;'a, b, c'
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 14 and column 13.
|
@@ -0,0 +1,131 @@
|
||||
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}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_functions_run_in_the_lane_vm() {
|
||||
register_double();
|
||||
|
||||
let expression = zen_expression::BatchExpression::standard("double(x) + count_distinct(items)").unwrap();
|
||||
assert!(expression.is_lane());
|
||||
let inputs: Vec<Variable> = (0..100)
|
||||
.map(|i| serde_json::json!({ "x": i, "items": [1, 1, 2, null] }).into())
|
||||
.collect();
|
||||
let results = expression.evaluate(&inputs);
|
||||
for (i, result) in results.into_iter().enumerate() {
|
||||
assert_eq!(result.unwrap().to_value(), serde_json::json!(i * 2 + 2));
|
||||
}
|
||||
|
||||
let program = zen_expression::lane::LaneProgram::standard("double('x')").unwrap();
|
||||
let err = zen_expression::lane::LaneRunner::new()
|
||||
.evaluate_one(&program, &zen_expression::Scope::default())
|
||||
.unwrap_err();
|
||||
let expected = Isolate::new().run_standard("double('x')").unwrap_err();
|
||||
assert_eq!(err.to_string(), expected.to_string());
|
||||
}
|
||||
@@ -182,7 +182,8 @@ string(mode([1.0, 1, 2]));;'1.0';question: equal values with different scales co
|
||||
string(mode([1, 1.0, 2]));;'1';question: equal values with different scales count together and the first spelling wins
|
||||
mode([]);;!error;question: mode of an empty list fails; could be null
|
||||
mode(null);;!error
|
||||
mode([1, null]);;!error
|
||||
mode([1, null]);;1
|
||||
mode([null, null]);;null
|
||||
mode(['a', 'a']);;'a'
|
||||
mode([true]);;!error
|
||||
mode(1);;!error
|
||||
|
||||
|
@@ -249,7 +249,7 @@ mode(list);{list: [-0.10, -0.1, 3]};-0.1
|
||||
mode(list);{list: [9223372036854775807, 9223372036854775807, 1]};9223372036854775807
|
||||
mode(list);{list: [1, 2, 3]};3;question: ties resolve to the largest value
|
||||
mode(list);{list: []};!error
|
||||
mode(list);{list: [null]};!error
|
||||
mode(list);{list: [null]};null
|
||||
# number and isNumeric over input strings
|
||||
number(s);{s: '1.5'};1.5
|
||||
number(s);{s: ' 42 '};42
|
||||
|
||||
|
@@ -584,7 +584,7 @@ mode(x);{x: {}};!error
|
||||
mode(x);{x: {a: 1}};!error
|
||||
mode(x);{};!error
|
||||
# mode: element types
|
||||
mode(x);{x: [1, null]};!error
|
||||
mode(x);{x: [1, null]};1
|
||||
mode(x);{x: [1, '2']};!error
|
||||
mode(x);{x: [true]};!error
|
||||
mode(x);{x: [[1], 2]};!error
|
||||
|
||||
|
Reference in New Issue
Block a user