fix(GRL-823): list functions in ZEN expressions; negative indexes count from the end

take, takeLast, find, findLast, findIndex, findLastIndex (-1 when none),
sort and sortBy ('asc' or 'desc', stable, nulls last) and isEmpty. find,
findIndex and sortBy take a callback with # or a name given with 'as'.

items[-1] is the last item, as documented, on the stack VM and the lane
VM (a string counts from its end too); a negative index past the start is
null. The spec rows that recorded the bug, the policy spec case and its
golden now expect the value.
This commit is contained in:
Ivan Miletic
2026-11-27 11:21:02 +01:00
parent 4d9cb32d2e
commit 13d2b84888
17 changed files with 394 additions and 77 deletions
@@ -127,7 +127,7 @@
],
[
{customer: {companies: []}},
"!error: ExpressionFailed",
{customer: {companies: [], first: null, second: -1, lastCompanyDepts: 0}},
],
],
}
+109
View File
@@ -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<Option<usize>> {
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<Item = &V> {
items.iter().filter(|v| !matches!(v, V::Null))
}
@@ -320,3 +330,102 @@ pub(crate) fn arg_extreme(items: &[V], max: bool) -> anyhow::Result<V> {
}
Ok(best.map_or(V::Null, |(value, _, _)| value.clone()))
}
pub(crate) fn find_index(items: &[V], last: bool) -> anyhow::Result<V> {
let mut found: Option<usize> = 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<Option<SortKey<'_>>> {
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<SortKey>,
b: &Option<SortKey>,
descending: bool,
) -> anyhow::Result<Ordering> {
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<Option<SortKey>>, descending: bool) -> anyhow::Result<Vec<usize>> {
for window in keys
.iter()
.filter(|k| k.is_some())
.collect::<Vec<_>>()
.windows(2)
{
compare_keys(window[0], window[1], false)?;
}
let mut order: Vec<usize> = (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<V> {
let keys = items
.iter()
.map(sort_key)
.collect::<anyhow::Result<Vec<_>>>()?;
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<V> {
let pairs = pairs(items)?;
let keys = pairs
.iter()
.map(|(_, key)| sort_key(key))
.collect::<anyhow::Result<Vec<_>>>()?;
let order = sorted_by_keys(keys, descending)?;
Ok(V::from_array(
order.into_iter().map(|i| pairs[i].0.clone()).collect(),
))
}
+144 -20
View File
@@ -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<dyn FunctionDefinition> {
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<dyn FunctionDefinition> {
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<V> {
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<V> {
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<V> {
__internal_aggregate(args, |items| aggregate::find_index(items, false))
}
pub fn find_last_index(args: Arguments) -> anyhow::Result<V> {
__internal_aggregate(args, |items| aggregate::find_index(items, true))
}
fn __internal_direction(args: &Arguments, pos: usize) -> anyhow::Result<bool> {
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<V> {
let descending = __internal_direction(&args, 1)?;
__internal_aggregate(args, |items| aggregate::sort(items, descending))
}
pub fn sort_by(args: Arguments) -> anyhow::Result<V> {
let descending = __internal_direction(&args, 1)?;
__internal_aggregate(args, |items| aggregate::sort_by(items, descending))
}
pub fn is_empty(args: Arguments) -> anyhow::Result<V> {
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<V> {
let a = args.var(0)?;
Ok(V::String(a.type_name().into()))
+1 -5
View File
@@ -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 {
+13 -2
View File
@@ -54,7 +54,9 @@ fn root(value: Decimal) -> Option<Decimal> {
}
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)));
@@ -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 => {
"<T>(array: T[], filter: Callback<T, boolean>) -> T | <T, U>(array: T[], value: Callback<T, U>, filter: Callback<T, boolean>) -> U"
}
F::Find | F::FindLast => "<T>(array: T[], condition: Callback<T, boolean>) -> T",
F::FindIndex | F::FindLastIndex => {
"<T>(array: T[], condition: Callback<T, boolean>) -> number"
}
F::SortBy => "<T>(array: T[], key: Callback<T, any>, direction?: string) -> T[]",
F::ArgMax | F::ArgMin => {
"<T>(array: T[], key: Callback<T, any>) -> T | <T, U>(array: T[], value: Callback<T, U>, key: Callback<T, any>, filter?: Callback<T, boolean>) -> U"
}
@@ -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,
@@ -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;
+7 -6
View File
@@ -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),
+17 -6
View File
@@ -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))])
}
+10 -8
View File
@@ -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),
+12 -11
View File
@@ -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 {
@@ -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
1 expression (string);input (json 5);output (json 5);note
19 a[0];{a: {'0': 'z'}};null
20 a[0];{a: {}};null
21 # Negative indexes count from the end (documented: items[-1] is the last item)
22 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[-1];{a: [1, 2, 3]};3
23 a[-2];{a: [1, 2, 3]};2;bug: negative indexes should count from the end a[-2];{a: [1, 2, 3]};2
24 a[-3];{a: [1, 2, 3]};1;bug: negative indexes should count from the end a[-3];{a: [1, 2, 3]};1
25 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[-4];{a: [1, 2, 3]};null
26 a[-1];{a: []};null;bug: negative index on an empty array should be null a[-1];{a: []};null
27 a[-1];{a: null};null
28 a[-1];{};null
29 [1, 2, 3][-1];;3;bug: docs say items[-1] is the last item [1, 2, 3][-1];;3
30 a[-1].x;{a: [{x: 1}, {x: 2}]};2;bug: negative indexes should count from the end a[-1].x;{a: [{x: 1}, {x: 2}]};2
31 # Dynamic indexes
32 a[i];{a: [10, 20, 30], i: 0};10
33 a[i];{a: [10, 20, 30], i: 2};30
35 a[i];{a: [10, 20, 30], i: null};null
36 a[i];{a: [10, 20, 30]};null
37 a[i];{a: [10, 20, 30], i: '1'};null
38 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
39 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
40 a[1+1];{a: [10, 20, 30]};30
41 a[len(a)-1];{a: [10, 20, 30]};30
42 a[len(a)-1];{a: [7]};7
43 a[len(a)];{a: [10, 20, 30]};null
44 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
45 a[b[0]];{a: [10, 20], b: [1]};20
46 a[a[0]];{a: [2, 0, 9]};9
47 # Decimal indexes are truncated
85 s[i];{s: 'hello', i: 9};null
86 s[i];{s: 'hello', i: null};null
87 s[i];{s: 'hello', i: '1'};null
88 s[-1];{s: 'hello'};'o';bug: negative index on a string should count from the end s[-1];{s: 'hello'};'o'
89 s[i];{s: 'hello', i: -1};'o';bug: negative index on a string should count from the end s[i];{s: 'hello', i: -1};'o'
90 s[1.5];{s: 'hello'};'e';question: a fractional string index truncates
91 s['0'];{s: 'hello'};null
92 s.x;{s: 'hello'};null
@@ -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: [[], []]};[]
1 expression (string);input (json 5);output (json 5);note
103 map(m
104 map(m
105 map(m
106 map(m
107 flatten(m);{m: [[1
108 flatten(m);{m: [[1]
109 flatten(m);{m: [[]
@@ -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}
1 expression (string) input (json 5) output (json 5) note
515 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}
516 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}
517 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}
518 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: null, last: null, n: 0, same: true}
519 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}
520 # Reshaping: rename and default fields into a new object
521 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}
@@ -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
1 expression (string);input (json 5);output (json 5);note
244 $[0] == 1;{$: [2
245 $[0] == 1;{$: []};false
246 $[0] == 1;{$: null};false
247 $[-1] == 2;{$: [1
248 $[-1] == 2;{$: [2
249 $[-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;{$: [2]};true
250 $[-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;{$: []};false
251 len($) == 0;{$: []};true
252 len($) == 0;{$: [1]};false
253 len($) == 0;{$: ''};true