diff --git a/core/engine/tests/golden/spec-policy/21-relationships-deep.jsonl.gz b/core/engine/tests/golden/spec-policy/21-relationships-deep.jsonl.gz index e6389440..31176a42 100644 Binary files a/core/engine/tests/golden/spec-policy/21-relationships-deep.jsonl.gz and b/core/engine/tests/golden/spec-policy/21-relationships-deep.jsonl.gz differ diff --git a/core/engine/tests/spec/policy/21-relationships-deep.json5 b/core/engine/tests/spec/policy/21-relationships-deep.json5 index 0f35fe4b..d80533ee 100644 --- a/core/engine/tests/spec/policy/21-relationships-deep.json5 +++ b/core/engine/tests/spec/policy/21-relationships-deep.json5 @@ -127,7 +127,7 @@ ], [ {customer: {companies: []}}, - "!error: ExpressionFailed", + {customer: {companies: [], first: null, second: -1, lastCompanyDepts: 0}}, ], ], } diff --git a/core/expression/src/functions/aggregate.rs b/core/expression/src/functions/aggregate.rs index aff542af..56163a35 100644 --- a/core/expression/src/functions/aggregate.rs +++ b/core/expression/src/functions/aggregate.rs @@ -13,6 +13,16 @@ use std::collections::BTreeMap; use std::rc::Rc; use std::str::FromStr; +pub(crate) fn index(n: Decimal, len: usize) -> Option> { + match n.to_usize() { + Some(index) => Some(Some(index)), + None => match n.to_i64() { + Some(back) if back < 0 => Some(len.checked_sub(back.unsigned_abs() as usize)), + _ => None, + }, + } +} + pub(crate) fn present(items: &[V]) -> impl Iterator { items.iter().filter(|v| !matches!(v, V::Null)) } @@ -320,3 +330,102 @@ pub(crate) fn arg_extreme(items: &[V], max: bool) -> anyhow::Result { } Ok(best.map_or(V::Null, |(value, _, _)| value.clone())) } + +pub(crate) fn find_index(items: &[V], last: bool) -> anyhow::Result { + let mut found: Option = None; + for (index, item) in items.iter().enumerate() { + match item { + V::Bool(true) => { + found = Some(index); + if !last { + break; + } + } + V::Bool(false) => {} + other => bail!("Expected a condition, got a {}", other.type_name()), + } + } + Ok(V::Number(match found { + Some(index) => Decimal::from(index), + None => Decimal::NEGATIVE_ONE, + })) +} + +enum SortKey<'a> { + Number(Decimal), + Text(&'a str), + Date(&'a VmDate), +} + +fn sort_key(value: &V) -> anyhow::Result>> { + Ok(Some(match value { + V::Null => return Ok(None), + V::Number(n) => SortKey::Number(*n), + V::String(s) => SortKey::Text(s.as_str()), + other => match date_of(other) { + Some(date) => SortKey::Date(date), + None => bail!("Cannot sort a {}", other.type_name()), + }, + })) +} + +fn compare_keys( + a: &Option, + b: &Option, + descending: bool, +) -> anyhow::Result { + Ok(match (a, b) { + (None, None) => Ordering::Equal, + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(a), Some(b)) => { + let ordering = match (a, b) { + (SortKey::Number(a), SortKey::Number(b)) => a.cmp(b), + (SortKey::Text(a), SortKey::Text(b)) => a.cmp(b), + (SortKey::Date(a), SortKey::Date(b)) => a.cmp(b), + _ => bail!("Cannot sort values of different types"), + }; + match descending { + true => ordering.reverse(), + false => ordering, + } + } + }) +} + +fn sorted_by_keys(keys: Vec>, descending: bool) -> anyhow::Result> { + for window in keys + .iter() + .filter(|k| k.is_some()) + .collect::>() + .windows(2) + { + compare_keys(window[0], window[1], false)?; + } + let mut order: Vec = (0..keys.len()).collect(); + order.sort_by(|a, b| compare_keys(&keys[*a], &keys[*b], descending).unwrap_or(Ordering::Equal)); + Ok(order) +} + +pub(crate) fn sort(items: &[V], descending: bool) -> anyhow::Result { + let keys = items + .iter() + .map(sort_key) + .collect::>>()?; + let order = sorted_by_keys(keys, descending)?; + Ok(V::from_array( + order.into_iter().map(|i| items[i].clone()).collect(), + )) +} + +pub(crate) fn sort_by(items: &[V], descending: bool) -> anyhow::Result { + let pairs = pairs(items)?; + let keys = pairs + .iter() + .map(|(_, key)| sort_key(key)) + .collect::>>()?; + let order = sorted_by_keys(keys, descending)?; + Ok(V::from_array( + order.into_iter().map(|i| pairs[i].0.clone()).collect(), + )) +} diff --git a/core/expression/src/functions/internal.rs b/core/expression/src/functions/internal.rs index 861278da..18d848b0 100644 --- a/core/expression/src/functions/internal.rs +++ b/core/expression/src/functions/internal.rs @@ -71,6 +71,15 @@ pub enum InternalFunction { ArgMax, #[strum(to_string = "argMin", serialize = "minBy")] ArgMin, + Take, + TakeLast, + Find, + FindLast, + FindIndex, + FindLastIndex, + Sort, + SortBy, + IsEmpty, #[strum(serialize = "@sum")] AggregateSum, #[strum(serialize = "@avg")] @@ -152,6 +161,9 @@ impl InternalFunction { ) => &[C, C], (IF::Percentile | IF::PercentileApprox | IF::TopK, 3) => &[C, P], (IF::Percentile | IF::PercentileApprox | IF::TopK, 4) => &[C, P, C], + (IF::Find | IF::FindLast | IF::FindIndex | IF::FindLastIndex, 2) => &[C], + (IF::SortBy, 2) => &[C], + (IF::SortBy, 3) => &[C, P], (IF::ArgMax | IF::ArgMin, 2) => &[C], (IF::ArgMax | IF::ArgMin, 3) => &[C, C], (IF::ArgMax | IF::ArgMin, 4) => &[C, C, C], @@ -460,25 +472,29 @@ impl From<&InternalFunction> for Rc { signature: FunctionSignature::single(VT::Number.array(), VT::Number), }), - IF::Stddev | IF::Variance | IF::StddevPop | IF::VariancePop | IF::Skew - | IF::Kurtosis | IF::AggregateAvg | IF::AggregateMedian => { - Rc::new(StaticFunction { - implementation: Rc::new(match value { - IF::Stddev => imp::stddev, - IF::Variance => imp::variance, - IF::StddevPop => imp::stddev_pop, - IF::VariancePop => imp::variance_pop, - IF::Skew => imp::skew, - IF::Kurtosis => imp::kurtosis, - IF::AggregateAvg => imp::aggregate_avg, - _ => imp::aggregate_median, - }), - signature: FunctionSignature::single( - VT::Nullable(Rc::new(VT::Number)).array(), - VT::Nullable(Rc::new(VT::Number)), - ), - }) - } + IF::Stddev + | IF::Variance + | IF::StddevPop + | IF::VariancePop + | IF::Skew + | IF::Kurtosis + | IF::AggregateAvg + | IF::AggregateMedian => Rc::new(StaticFunction { + implementation: Rc::new(match value { + IF::Stddev => imp::stddev, + IF::Variance => imp::variance, + IF::StddevPop => imp::stddev_pop, + IF::VariancePop => imp::variance_pop, + IF::Skew => imp::skew, + IF::Kurtosis => imp::kurtosis, + IF::AggregateAvg => imp::aggregate_avg, + _ => imp::aggregate_median, + }), + signature: FunctionSignature::single( + VT::Nullable(Rc::new(VT::Number)).array(), + VT::Nullable(Rc::new(VT::Number)), + ), + }), IF::Percentile | IF::PercentileApprox => Rc::new(StaticFunction { implementation: Rc::new(match value { @@ -561,6 +577,52 @@ impl From<&InternalFunction> for Rc { signature: FunctionSignature::single(VT::Any.array(), VT::Any), }), + IF::Take | IF::TakeLast => Rc::new(StaticFunction { + implementation: Rc::new(match value { + IF::Take => imp::take, + _ => imp::take_last, + }), + signature: FunctionSignature { + parameters: vec![VT::Any.array(), VT::Number], + return_type: VT::Any.array(), + }, + }), + + IF::Find | IF::FindLast => Rc::new(StaticFunction { + implementation: Rc::new(match value { + IF::Find => imp::first, + _ => imp::last, + }), + signature: FunctionSignature::single(VT::Any.array(), VT::Any), + }), + + IF::FindIndex | IF::FindLastIndex => Rc::new(StaticFunction { + implementation: Rc::new(match value { + IF::FindIndex => imp::find_index, + _ => imp::find_last_index, + }), + signature: FunctionSignature::single(VT::Any.array(), VT::Number), + }), + + IF::Sort | IF::SortBy => Rc::new(CompositeFunction { + implementation: Rc::new(match value { + IF::Sort => imp::sort, + _ => imp::sort_by, + }), + signatures: vec![ + FunctionSignature::single(VT::Any.array(), VT::Any.array()), + FunctionSignature { + parameters: vec![VT::Any.array(), VT::String], + return_type: VT::Any.array(), + }, + ], + }), + + IF::IsEmpty => Rc::new(StaticFunction { + implementation: Rc::new(imp::is_empty), + signature: FunctionSignature::single(VT::Any, VT::Bool), + }), + IF::Type => Rc::new(StaticFunction { implementation: Rc::new(imp::to_type), signature: FunctionSignature::single(VT::Any, VT::String), @@ -844,7 +906,10 @@ pub(crate) mod imp { } Ok(V::from_array(out)) } - _ => Err(anyhow!("Similarity not available for type {}", a.type_name())), + _ => Err(anyhow!( + "Similarity not available for type {}", + a.type_name() + )), } } @@ -1230,6 +1295,65 @@ pub(crate) mod imp { __internal_aggregate(args, |items| aggregate::arg_extreme(items, false)) } + pub fn take(args: Arguments) -> anyhow::Result { + let n = aggregate::count(args.var(1)?, 1)?; + __internal_aggregate(args, |items| { + Ok(V::from_array(items.iter().take(n).cloned().collect())) + }) + } + + pub fn take_last(args: Arguments) -> anyhow::Result { + let n = aggregate::count(args.var(1)?, 1)?; + __internal_aggregate(args, |items| { + Ok(V::from_array( + items[items.len().saturating_sub(n)..].to_vec(), + )) + }) + } + + pub fn find_index(args: Arguments) -> anyhow::Result { + __internal_aggregate(args, |items| aggregate::find_index(items, false)) + } + + pub fn find_last_index(args: Arguments) -> anyhow::Result { + __internal_aggregate(args, |items| aggregate::find_index(items, true)) + } + + fn __internal_direction(args: &Arguments, pos: usize) -> anyhow::Result { + match args.ostr(pos)? { + None | Some("asc") => Ok(false), + Some("desc") => Ok(true), + Some(other) => Err(anyhow!("Expected 'asc' or 'desc', got '{other}'")), + } + } + + pub fn sort(args: Arguments) -> anyhow::Result { + let descending = __internal_direction(&args, 1)?; + __internal_aggregate(args, |items| aggregate::sort(items, descending)) + } + + pub fn sort_by(args: Arguments) -> anyhow::Result { + let descending = __internal_direction(&args, 1)?; + __internal_aggregate(args, |items| aggregate::sort_by(items, descending)) + } + + pub fn is_empty(args: Arguments) -> anyhow::Result { + let a = args.var(0)?; + let empty = match a { + V::Null => true, + V::String(s) => s.is_empty(), + V::Array(items) => items.borrow().is_empty(), + V::Object(map) => map.borrow().is_empty(), + other => { + return Err(anyhow!( + "Cannot tell whether a {} is empty", + other.type_name() + )) + } + }; + Ok(V::Bool(empty)) + } + 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/sketch.rs b/core/expression/src/functions/sketch.rs index a7c57f86..9da0ed25 100644 --- a/core/expression/src/functions/sketch.rs +++ b/core/expression/src/functions/sketch.rs @@ -55,11 +55,7 @@ impl Hll { pub fn estimate(&self) -> u64 { let m = HLL_REGISTERS as f64; let alpha = 0.7213 / (1.0 + 1.079 / m); - let sum: f64 = self - .registers - .iter() - .map(|r| 2f64.powi(-(*r as i32))) - .sum(); + let sum: f64 = self.registers.iter().map(|r| 2f64.powi(-(*r as i32))).sum(); let zeros = self.registers.iter().filter(|r| **r == 0).count(); let raw = alpha * m * m / sum; let estimate = if raw <= 2.5 * m && zeros > 0 { diff --git a/core/expression/src/functions/stats.rs b/core/expression/src/functions/stats.rs index b5a382cd..f195f9f1 100644 --- a/core/expression/src/functions/stats.rs +++ b/core/expression/src/functions/stats.rs @@ -54,7 +54,9 @@ fn root(value: Decimal) -> Option { } let mut x = guess; for _ in 0..4 { - x = x.checked_add(value.checked_div(x)?)?.checked_div(Decimal::TWO)?; + x = x + .checked_add(value.checked_div(x)?)? + .checked_div(Decimal::TWO)?; } Some(x) } @@ -192,7 +194,16 @@ mod tests { #[test] fn spreads_match_the_textbook() { - let values = [dec!(2), dec!(4), dec!(4), dec!(4), dec!(5), dec!(5), dec!(7), dec!(9)]; + let values = [ + dec!(2), + dec!(4), + dec!(4), + dec!(4), + dec!(5), + dec!(5), + dec!(7), + dec!(9), + ]; assert_eq!(variance(&values, false).unwrap(), Some(dec!(4))); assert_eq!(stddev(&values, false).unwrap(), Some(dec!(2))); assert_eq!(variance(&values, true).unwrap(), Some(dec!(4.571428571429))); diff --git a/core/expression/src/intellisense/completion.rs b/core/expression/src/intellisense/completion.rs index 79748fda..f7a48f47 100644 --- a/core/expression/src/intellisense/completion.rs +++ b/core/expression/src/intellisense/completion.rs @@ -431,6 +431,27 @@ fn function_info(fk: &FunctionKind) -> String { InternalFunction::Last => { "The last non-null item; last(items, #.ok) the last matching item; last(items, #.amount, #.ok) its projection" } + InternalFunction::Take => "The first n items of the array", + InternalFunction::TakeLast => "The last n items of the array", + InternalFunction::Find => { + "The first item matching a condition: find(items, #.status == 'declined')" + } + InternalFunction::FindLast => { + "The last item matching a condition: findLast(items, #.status == 'declined')" + } + InternalFunction::FindIndex => { + "The position of the first item matching a condition, -1 when none" + } + InternalFunction::FindLastIndex => { + "The position of the last item matching a condition, -1 when none" + } + InternalFunction::Sort => { + "Sorts numbers, strings or dates, 'asc' (default) or 'desc'; nulls go last" + } + InternalFunction::SortBy => { + "Sorts items by a key: sortBy(items, #.amount, 'desc'); stable, nulls go last" + } + InternalFunction::IsEmpty => "True for null, an empty string, array or object", InternalFunction::ArgMax => { "The item with the largest key: argMax(items, #.amount), or a projection of it: argMax(items, #.id, #.amount, #.ok)" } @@ -558,6 +579,14 @@ fn function_param_names(fk: &FunctionKind) -> Vec<&'static str> { vec!["arr", "fraction"] } InternalFunction::TopK => vec!["arr", "k"], + InternalFunction::Take | InternalFunction::TakeLast => vec!["arr", "n"], + InternalFunction::Find + | InternalFunction::FindLast + | InternalFunction::FindIndex + | InternalFunction::FindLastIndex => vec!["arr"], + InternalFunction::Sort => vec!["arr", "direction"], + InternalFunction::SortBy => vec!["pairs", "direction"], + InternalFunction::IsEmpty => vec!["value"], InternalFunction::ArgMax | InternalFunction::ArgMin => vec!["pairs"], InternalFunction::Rand => vec!["max"], InternalFunction::Round | InternalFunction::Trunc => vec!["num", "digits"], @@ -673,6 +702,11 @@ fn callback_forms(function: &InternalFunction) -> Option<&'static str> { F::First | F::Last => { "(array: T[], filter: Callback) -> T | (array: T[], value: Callback, filter: Callback) -> U" } + F::Find | F::FindLast => "(array: T[], condition: Callback) -> T", + F::FindIndex | F::FindLastIndex => { + "(array: T[], condition: Callback) -> number" + } + F::SortBy => "(array: T[], key: Callback, direction?: string) -> T[]", F::ArgMax | F::ArgMin => { "(array: T[], key: Callback) -> T | (array: T[], value: Callback, key: Callback, filter?: Callback) -> U" } diff --git a/core/expression/src/intellisense/type_provider.rs b/core/expression/src/intellisense/type_provider.rs index b0259979..fa74a46d 100644 --- a/core/expression/src/intellisense/type_provider.rs +++ b/core/expression/src/intellisense/type_provider.rs @@ -617,6 +617,12 @@ impl TypesProvider { | InternalFunction::Last | InternalFunction::Distinct | InternalFunction::TopK + | InternalFunction::Take + | InternalFunction::TakeLast + | InternalFunction::Sort + | InternalFunction::Find + | InternalFunction::FindLast + | InternalFunction::SortBy | InternalFunction::ArgMax | InternalFunction::ArgMin), ) => self.element_typecheck(*f, kind, &type_list, arguments), @@ -911,10 +917,23 @@ impl TypesProvider { other => VariableType::Nullable(Rc::new(other)), }; TypeInfo::from(match function { - InternalFunction::First | InternalFunction::Last => nullable(element), + InternalFunction::First + | InternalFunction::Last + | InternalFunction::Find + | InternalFunction::FindLast => nullable(element), InternalFunction::Distinct | InternalFunction::TopK => { VariableType::Array(Rc::new(element)) } + InternalFunction::Take | InternalFunction::TakeLast | InternalFunction::Sort => { + arg_types + .first() + .map(|t| t.unwrap_nullable().0.clone()) + .unwrap_or(VariableType::Any) + } + InternalFunction::SortBy => match element.iterator() { + Some(inner) => VariableType::Array(Rc::new(inner.unwrap_nullable().0.clone())), + None => VariableType::Any.array(), + }, _ => match element.iterator() { Some(inner) => nullable(inner.unwrap_nullable().0.clone()), None => VariableType::Any, diff --git a/core/expression/src/lane/builtins/registered.rs b/core/expression/src/lane/builtins/registered.rs index 50d4997c..e2934624 100644 --- a/core/expression/src/lane/builtins/registered.rs +++ b/core/expression/src/lane/builtins/registered.rs @@ -47,6 +47,15 @@ registered! { SOUNDEX = Soundex; JARO_WINKLER = JaroWinkler; TOKEN_SET_SIMILARITY = TokenSetSimilarity; + TAKE = Take; + TAKE_LAST = TakeLast; + FIND = Find; + FIND_LAST = FindLast; + FIND_INDEX = FindIndex; + FIND_LAST_INDEX = FindLastIndex; + SORT = Sort; + SORT_BY = SortBy; + IS_EMPTY = IsEmpty; STDDEV = Stddev; VARIANCE = Variance; STDDEV_POP = StddevPop; diff --git a/core/expression/src/lane/ops.rs b/core/expression/src/lane/ops.rs index 893c2cbe..0d969c80 100644 --- a/core/expression/src/lane/ops.rs +++ b/core/expression/src/lane/ops.rs @@ -35,16 +35,17 @@ impl Ops { match (Date::textual(a), Date::textual(b)) { (Object(o), String(s)) => Ok(o.borrow().get_str(s.as_str()).cloned().unwrap_or(Null)), (Array(a), Number(n)) => { - let index = n - .to_usize() + let a = a.borrow(); + let index = crate::functions::aggregate::index(n, a.len()) .ok_or_else(|| Self::error("Fetch", "Failed to convert to usize"))?; - Ok(a.borrow().get(index).cloned().unwrap_or(Null)) + Ok(index.and_then(|i| a.get(i)).cloned().unwrap_or(Null)) } (String(str), Number(n)) => { - let index = n - .to_usize() + let index = crate::functions::aggregate::index(n, str.len()) .ok_or_else(|| Self::error("Fetch", "Failed to convert to usize"))?; - let slice = index.checked_add(1).and_then(|end| str.get(index..end)); + let slice = index + .and_then(|index| index.checked_add(1).map(|end| (index, end))) + .and_then(|(index, end)| str.get(index..end)); Ok(slice.map_or(Null, |s| String(s.into()))) } _ => Ok(Null), diff --git a/core/expression/src/parser/parser.rs b/core/expression/src/parser/parser.rs index 3599deba..eab79a53 100644 --- a/core/expression/src/parser/parser.rs +++ b/core/expression/src/parser/parser.rs @@ -871,12 +871,14 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { Some(alias) } alias_token => { - errors.push(self.error(AstNodeError::Custom { - message: afmt!(self, "Expected identifier after 'as'"), - span: alias_token - .map(|t| t.span) - .unwrap_or((self.prev_token_end(), self.prev_token_end())), - })); + errors.push( + self.error(AstNodeError::Custom { + message: afmt!(self, "Expected identifier after 'as'"), + span: alias_token + .map(|t| t.span) + .unwrap_or((self.prev_token_end(), self.prev_token_end())), + }), + ); None } } @@ -987,6 +989,15 @@ impl<'arena, 'token_ref, Flavor> Parser<'arena, 'token_ref, Flavor> { (IF::First | IF::Last, [value, condition]) => { call(target, &[map(filter(list, condition), value)]) } + (IF::FindIndex | IF::FindLastIndex, [condition]) => { + call(target, &[map(list, condition)]) + } + (IF::Find | IF::FindLast, [condition]) => call(target, &[filter(list, condition)]), + (IF::SortBy, [key]) => call(target, &[map(list, pair(make(Node::Pointer), key))]), + (IF::SortBy, [key, direction]) => call( + target, + &[map(list, pair(make(Node::Pointer), key)), direction], + ), (IF::ArgMax | IF::ArgMin, [key]) => { call(target, &[map(list, pair(make(Node::Pointer), key))]) } diff --git a/core/expression/src/parser/unary.rs b/core/expression/src/parser/unary.rs index d7b6d9f8..c6f510a0 100644 --- a/core/expression/src/parser/unary.rs +++ b/core/expression/src/parser/unary.rs @@ -2,13 +2,13 @@ use crate::functions::{ ClosureFunction, DateMethod, DeprecatedFunction, FunctionKind, FunctionRegistry, InternalFunction, MethodKind, }; -use crate::variable::VariableType; use crate::lexer::{Bracket, ComparisonOperator, Identifier, LogicalOperator, Operator, TokenKind}; use crate::parser::ast::{AstNodeError, Node}; use crate::parser::constants::{Associativity, BINARY_OPERATORS, UNARY_OPERATORS}; use crate::parser::parser::{Parser, ParserContext}; use crate::parser::unary::UnaryNodeBehaviour::CompareWithReference; use crate::parser::{NodeMetadata, ParserResult}; +use crate::variable::VariableType; #[derive(Debug)] pub struct Unary; @@ -380,13 +380,15 @@ impl From<&Node<'_>> for UnaryNodeBehaviour { InternalFunction::Values => CompareWithReference(In), InternalFunction::Type => CompareWithReference(Equal), InternalFunction::Date => CompareWithReference(Equal), - other => match FunctionRegistry::get_definition(&FunctionKind::Internal(*other)) - .map(|definition| definition.return_type()) - { - Some(VariableType::Bool) => AsBoolean, - Some(VariableType::Array(_)) => CompareWithReference(In), - _ => CompareWithReference(Equal), - }, + other => { + match FunctionRegistry::get_definition(&FunctionKind::Internal(*other)) + .map(|definition| definition.return_type()) + { + Some(VariableType::Bool) => AsBoolean, + Some(VariableType::Array(_)) => CompareWithReference(In), + _ => CompareWithReference(Equal), + } + } }, FunctionKind::Deprecated(d) => match d { DeprecatedFunction::Date => CompareWithReference(Equal), diff --git a/core/expression/src/vm/vm.rs b/core/expression/src/vm/vm.rs index 57986062..c05075de 100644 --- a/core/expression/src/vm/vm.rs +++ b/core/expression/src/vm/vm.rs @@ -122,22 +122,23 @@ impl<'arena, 'parent_ref, 'bytecode_ref> VMInner<'parent_ref, 'bytecode_ref> { } (Array(a), Number(n)) => { let arr = a.borrow(); - self.push( - arr.get(n.to_usize().ok_or_else(|| OpcodeErr { + let index = crate::functions::aggregate::index(n, arr.len()) + .ok_or_else(|| OpcodeErr { opcode: "Fetch".into(), message: "Failed to convert to usize".into(), - })?) - .cloned() - .unwrap_or(Null), - ) + })?; + self.push(index.and_then(|i| arr.get(i)).cloned().unwrap_or(Null)) } (String(str), Number(n)) => { - let index = n.to_usize().ok_or_else(|| OpcodeErr { - opcode: "Fetch".into(), - message: "Failed to convert to usize".into(), - })?; + let index = crate::functions::aggregate::index(n, str.len()) + .ok_or_else(|| OpcodeErr { + opcode: "Fetch".into(), + message: "Failed to convert to usize".into(), + })?; - let slice = index.checked_add(1).and_then(|end| str.get(index..end)); + let slice = index + .and_then(|index| index.checked_add(1).map(|end| (index, end))) + .and_then(|(index, end)| str.get(index..end)); if let Some(slice) = slice { self.push(String((slice).into())); } else { diff --git a/core/expression/tests/spec/standard/04-index.csv b/core/expression/tests/spec/standard/04-index.csv index 51347c5b..991a6143 100644 --- a/core/expression/tests/spec/standard/04-index.csv +++ b/core/expression/tests/spec/standard/04-index.csv @@ -19,15 +19,15 @@ a[0];{a: true};null a[0];{a: {'0': 'z'}};null a[0];{a: {}};null # Negative indexes count from the end (documented: items[-1] is the last item) -a[-1];{a: [1, 2, 3]};3;bug: docs say items[-1] is the last item but the VM fails to convert -1 to usize -a[-2];{a: [1, 2, 3]};2;bug: negative indexes should count from the end -a[-3];{a: [1, 2, 3]};1;bug: negative indexes should count from the end -a[-4];{a: [1, 2, 3]};null;bug: a negative index past the start should be out of range (null) like a positive one -a[-1];{a: []};null;bug: negative index on an empty array should be null +a[-1];{a: [1, 2, 3]};3 +a[-2];{a: [1, 2, 3]};2 +a[-3];{a: [1, 2, 3]};1 +a[-4];{a: [1, 2, 3]};null +a[-1];{a: []};null a[-1];{a: null};null a[-1];{};null -[1, 2, 3][-1];;3;bug: docs say items[-1] is the last item -a[-1].x;{a: [{x: 1}, {x: 2}]};2;bug: negative indexes should count from the end +[1, 2, 3][-1];;3 +a[-1].x;{a: [{x: 1}, {x: 2}]};2 # Dynamic indexes a[i];{a: [10, 20, 30], i: 0};10 a[i];{a: [10, 20, 30], i: 2};30 @@ -35,13 +35,13 @@ a[i];{a: [10, 20, 30], i: 3};null a[i];{a: [10, 20, 30], i: null};null a[i];{a: [10, 20, 30]};null a[i];{a: [10, 20, 30], i: '1'};null -a[i];{a: [10, 20, 30], i: -1};30;bug: negative dynamic index should count from the end +a[i];{a: [10, 20, 30], i: -1};30 a[i];{a: [10, 20, 30], i: 99999999999999999999};null;bug: an index beyond usize should be out of range (null) like any other large index a[1+1];{a: [10, 20, 30]};30 a[len(a)-1];{a: [10, 20, 30]};30 a[len(a)-1];{a: [7]};7 a[len(a)];{a: [10, 20, 30]};null -a[len(a)-1];{a: []};null;bug: len(a)-1 on an empty array is -1 which should index as out of range (null) +a[len(a)-1];{a: []};null a[b[0]];{a: [10, 20], b: [1]};20 a[a[0]];{a: [2, 0, 9]};9 # Decimal indexes are truncated @@ -85,8 +85,8 @@ s[i];{s: 'hello', i: 1};'e' s[i];{s: 'hello', i: 9};null s[i];{s: 'hello', i: null};null s[i];{s: 'hello', i: '1'};null -s[-1];{s: 'hello'};'o';bug: negative index on a string should count from the end -s[i];{s: 'hello', i: -1};'o';bug: negative index on a string should count from the end +s[-1];{s: 'hello'};'o' +s[i];{s: 'hello', i: -1};'o' s[1.5];{s: 'hello'};'e';question: a fractional string index truncates s['0'];{s: 'hello'};null s.x;{s: 'hello'};null diff --git a/core/expression/tests/spec/standard/13-01-nested-paths.csv b/core/expression/tests/spec/standard/13-01-nested-paths.csv index 26beaa7c..303e0435 100644 --- a/core/expression/tests/spec/standard/13-01-nested-paths.csv +++ b/core/expression/tests/spec/standard/13-01-nested-paths.csv @@ -103,7 +103,7 @@ map(m, len(#));{m: null};!error map(m, #[len(#) - 1]);{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[3, 6, 9] map(m, #[len(#) - 1]);{m: [[[1, 2]], [[3]]]};[[1, 2], [3]] map(m, #[len(#) - 1]);{m: [[1, 2], [5]]};[2, 5] -map(m, #[len(#) - 1]);{m: [[1], []]};[1, null];bug: negative indexes should count from the end +map(m, #[len(#) - 1]);{m: [[1], []]};[1, null] flatten(m);{m: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]};[1, 2, 3, 4, 5, 6, 7, 8, 9] flatten(m);{m: [[1], [], [7, 8]]};[1, 7, 8] flatten(m);{m: [[], []]};[] diff --git a/core/expression/tests/spec/standard/17-01-realistic.csv b/core/expression/tests/spec/standard/17-01-realistic.csv index 4e936388..7f0f0667 100644 --- a/core/expression/tests/spec/standard/17-01-realistic.csv +++ b/core/expression/tests/spec/standard/17-01-realistic.csv @@ -515,7 +515,7 @@ expression (string);input (json 5);output (json 5);note "first = items[0]; last = items[len(items) - 1]; summary = {first: first.name, last: last.name, n: len(items), same: first.name == last.name}; summary";{items: [{name: 'x'}, {name: 'x'}]};{first: 'x', last: 'x', n: 2, same: true} "first = items[0]; last = items[len(items) - 1]; summary = {first: first.name, last: last.name, n: len(items), same: first.name == last.name}; summary";{items: [{}, {name: 'z'}]};{first: null, last: 'z', n: 2, same: false} "first = items[0]; last = items[len(items) - 1]; summary = {first: first.name, last: last.name, n: len(items), same: first.name == last.name}; summary";{items: [1, 2]};{first: null, last: null, n: 2, same: true} -"first = items[0]; last = items[len(items) - 1]; summary = {first: first.name, last: last.name, n: len(items), same: first.name == last.name}; summary";{items: []};!error +"first = items[0]; last = items[len(items) - 1]; summary = {first: first.name, last: last.name, n: len(items), same: first.name == last.name}; summary";{items: []};{first: null, last: null, n: 0, same: true} "first = items[0]; last = items[len(items) - 1]; summary = {first: first.name, last: last.name, n: len(items), same: first.name == last.name}; summary";{items: 'ab'};{first: null, last: null, n: 2, same: true} # Reshaping: rename and default fields into a new object "src = profile ?? {}; out.fullName = (src.first ?? '') + ' ' + (src.last ?? ''); out.email = lower(src.email ?? 'none'); out.age = src.age ?? 0; out.adult = out.age >= 18; out";{profile: {first: 'Ann', last: 'Lee', email: 'A@X.IO', age: 30}};{fullName: 'Ann Lee', email: 'a@x.io', age: 30, adult: true} diff --git a/core/expression/tests/spec/unary/06-reference.csv b/core/expression/tests/spec/unary/06-reference.csv index caba49ff..d2029ace 100644 --- a/core/expression/tests/spec/unary/06-reference.csv +++ b/core/expression/tests/spec/unary/06-reference.csv @@ -244,10 +244,10 @@ $[0] == 1;{$: [1, 2]};true $[0] == 1;{$: [2, 1]};false $[0] == 1;{$: []};false $[0] == 1;{$: null};false -$[-1] == 2;{$: [1, 2]};true;bug: docs say items[-1] is the last item but the VM fails to convert -1 to usize (same as standard mode) -$[-1] == 2;{$: [2, 1]};false;bug: docs say items[-1] is the last item but the VM fails to convert -1 to usize (same as standard mode) -$[-1] == 2;{$: [2]};true;bug: docs say items[-1] is the last item but the VM fails to convert -1 to usize (same as standard mode) -$[-1] == 2;{$: []};false;bug: docs say items[-1] is the last item but the VM fails to convert -1 to usize (same as standard mode) +$[-1] == 2;{$: [1, 2]};true +$[-1] == 2;{$: [2, 1]};false +$[-1] == 2;{$: [2]};true +$[-1] == 2;{$: []};false len($) == 0;{$: []};true len($) == 0;{$: [1]};false len($) == 0;{$: ''};true